Skip to content

Commit

Permalink
Merge branch 'develop' into feat/health-check-endpoint
Browse files Browse the repository at this point in the history
# Conflicts:
#	src/app.module.ts
  • Loading branch information
AndersonCRocha committed May 17, 2024
2 parents 5d896c3 + a4be895 commit 451e986
Show file tree
Hide file tree
Showing 25 changed files with 357 additions and 41 deletions.
12 changes: 6 additions & 6 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = {
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'plugin:jest/recommended'
'plugin:jest/recommended',
],
root: true,
env: {
Expand All @@ -25,14 +25,14 @@ module.exports = {
'jest/expect-expect': [
'warn',
{
'assertFunctionNames': ['expect', 'request.**.expect'],
}
assertFunctionNames: ['expect', 'request.**.expect'],
},
],
'prettier/prettier': [
'error',
{
'endOfLine': 'auto'
}
]
endOfLine: 'auto',
},
],
},
};
8 changes: 4 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
branches:
- main
tags:
- "*"
- '*'
pull_request:
branches:
- main
Expand All @@ -21,10 +21,10 @@ jobs:
- name: Checkout Source
uses: actions/checkout@v4
# Setup node.js and cache
- name: "Setup node.js"
- name: 'Setup node.js'
uses: actions/setup-node@v4
with:
node-version: "18.x"
node-version: '18.x'
cache: 'npm'
cache-dependency-path: ./package-lock.json
# Install dependencies
Expand All @@ -38,4 +38,4 @@ jobs:
run: npm run build

- name: Test
run: npm test
run: npm test
34 changes: 34 additions & 0 deletions .github/workflows/dev.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Deploy Backend in Development Enviroment

on:
push:
branches: [develop]

jobs:
build:
runs-on: dev

steps:
- uses: actions/checkout@v4

- name: Create .env file
run: |
touch .env
echo TZ=${{ secrets.TZ }} >> .env
echo DB_HOST=${{ secrets.DB_HOST }} >> .env
echo DB_PORT=${{ secrets.DB_PORT }} >> .env
echo DB_USER=${{ secrets.DB_USER }} >> .env
echo DB_PASSWORD=${{ secrets.DB_PASSWORD }} >> .env
echo DB_DATABASE_NAME=${{ secrets.DEV_DB_DATABASE_NAME }} >> .env
echo DATABASE_URL=postgresql://${{ secrets.DB_USER }}:${{ secrets.DB_PASSWORD }}@${{ secrets.DB_HOST }}:${{ secrets.DB_PORT }}/${{ secrets.DEV_DB_DATABASE_NAME }}?schema=public >> .env
echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env
echo HOST=${{ secrets.HOST }} >> .env
echo PORT=${{ secrets.PORT }} >> .env
echo SERVER_USER_PASSWORD=${{ secrets.SERVER_USER_PASSWORD }} >> .env
cat .env
- name: Remove old docker image
run: echo ${{ secrets.SERVER_USER_PASSWORD }} | sudo -S docker compose down --rmi all

- name: Create new docker image
run: echo ${{ secrets.SERVER_USER_PASSWORD }} | sudo -S docker compose up -d --force-recreate
34 changes: 34 additions & 0 deletions .github/workflows/staging.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Deploy Backend in Development Enviroment

on:
push:
branches: [staging]

jobs:
build:
runs-on: stg

steps:
- uses: actions/checkout@v4

- name: Create .env file
run: |
touch .env
echo TZ=${{ secrets.TZ }} >> .env
echo DB_HOST=${{ secrets.DB_HOST }} >> .env
echo DB_PORT=${{ secrets.DB_PORT }} >> .env
echo DB_USER=${{ secrets.DB_USER }} >> .env
echo DB_PASSWORD=${{ secrets.DB_PASSWORD }} >> .env
echo DB_DATABASE_NAME=${{ secrets.STG_DB_DATABASE_NAME }} >> .env
echo DATABASE_URL=postgresql://${{ secrets.DB_USER }}:${{ secrets.DB_PASSWORD }}@${{ secrets.DB_HOST }}:${{ secrets.DB_PORT }}/${{ secrets.STG_DB_DATABASE_NAME }}?schema=public >> .env
echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env
echo HOST=${{ secrets.HOST }} >> .env
echo PORT=${{ secrets.PORT }} >> .env
echo SERVER_USER_PASSWORD=${{ secrets.SERVER_USER_PASSWORD }} >> .env
cat .env
- name: Remove old docker image
run: echo ${{ secrets.SERVER_USER_PASSWORD }} | sudo -S docker compose down --rmi all

- name: Create new docker image
run: echo ${{ secrets.SERVER_USER_PASSWORD }} | sudo -S docker compose up -d --force-recreate
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"start:prod": "node dist/src/main.js",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"lint:ci": "eslint \"{src,apps,libs,test}/**/*.ts\" --format=stylish",
"test": "jest",
Expand Down
14 changes: 14 additions & 0 deletions prisma/migrations/20240516212629_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
-- CreateTable
CREATE TABLE "supporters" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"image_url" TEXT NOT NULL,
"link" TEXT NOT NULL,
"created_at" VARCHAR(32) NOT NULL,
"updated_at" VARCHAR(32),

CONSTRAINT "supporters_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "supporters_name_key" ON "supporters"("name");
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- This is an empty migration.

CREATE EXTENSION IF NOT EXISTS unaccent;
6 changes: 6 additions & 0 deletions prisma/migrations/20240517192040_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- CreateEnum
CREATE TYPE "ShelterCategory" AS ENUM ('Shelter', 'DistributionCenter');

-- AlterTable
ALTER TABLE "shelters" ADD COLUMN "actived" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN "category" "ShelterCategory" NOT NULL DEFAULT 'Shelter';
40 changes: 29 additions & 11 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ enum AccessLevel {
Admin
}

enum ShelterCategory {
Shelter
DistributionCenter
}

model User {
id String @id @default(uuid())
name String
Expand Down Expand Up @@ -85,25 +90,27 @@ model Supply {
}

model Shelter {
id String @id @default(uuid())
name String @unique
pix String? @unique
id String @id @default(uuid())
name String @unique
pix String? @unique
address String
street String?
neighbourhood String?
city String?
streetNumber String? @map("street_number")
zipCode String? @map("zip_code")
petFriendly Boolean? @map("pet_friendly")
shelteredPeople Int? @map("sheltered_people")
streetNumber String? @map("street_number")
zipCode String? @map("zip_code")
petFriendly Boolean? @map("pet_friendly")
shelteredPeople Int? @map("sheltered_people")
capacity Int?
contact String?
prioritySum Int @default(value: 0) @map("priority_sum")
prioritySum Int @default(value: 0) @map("priority_sum")
latitude Float?
longitude Float?
verified Boolean @default(value: false)
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)
verified Boolean @default(value: false)
category ShelterCategory @default(value: Shelter)
actived Boolean @default(value: true)
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)
shelterManagers ShelterManagers[]
shelterSupplies ShelterSupply[]
Expand Down Expand Up @@ -133,3 +140,14 @@ model Partners {
@@map("partners")
}

model Supporters {
id String @id @default(uuid())
name String @unique
imageUrl String @map("image_url")
link String
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)
@@map("supporters")
}
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { SupplyCategoriesModule } from './supply-categories/supply-categories.mo
import { ShelterManagersModule } from './shelter-managers/shelter-managers.module';
import { ShelterSupplyModule } from './shelter-supply/shelter-supply.module';
import { PartnersModule } from './partners/partners.module';
import { SupportersModule } from './supporters/supporters.module';
import { HealthModule } from './health/health.module';

@Module({
Expand All @@ -25,6 +26,7 @@ import { HealthModule } from './health/health.module';
ShelterManagersModule,
ShelterSupplyModule,
PartnersModule,
SupportersModule,
HealthModule,
],
controllers: [],
Expand Down
23 changes: 22 additions & 1 deletion src/partners/partners.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { Controller, Get, HttpException, Logger } from '@nestjs/common';
import {
Body,
Controller,
Get,
HttpException,
Logger,
Post,
UseGuards,
} from '@nestjs/common';
import { PartnersService } from './partners.service';
import { ServerResponse } from '../utils';
import { AdminGuard } from '@/guards/admin.guard';

@Controller('partners')
export class PartnersController {
Expand All @@ -18,4 +27,16 @@ export class PartnersController {
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}

@Post('')
@UseGuards(AdminGuard)
async store(@Body() body) {
try {
await this.partnersService.store(body);
return new ServerResponse(200, 'Successfully created partner');
} catch (err: any) {
this.logger.error(`Failed to create partner: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}
}
9 changes: 9 additions & 0 deletions src/partners/partners.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Injectable } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';

import { PrismaService } from '../prisma/prisma.service';
import { z } from 'zod';
import { CreatePartnerSchema } from './types';

@ApiTags('Parceiros')
@Injectable()
Expand All @@ -11,4 +13,11 @@ export class PartnersService {
async index() {
return await this.prismaService.partners.findMany({});
}

async store(body: z.infer<typeof CreatePartnerSchema>) {
const payload = CreatePartnerSchema.parse(body);
await this.prismaService.partners.create({
data: { ...payload, createdAt: new Date().toISOString() },
});
}
}
17 changes: 17 additions & 0 deletions src/partners/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import z from 'zod';

const PartnerSchema = z.object({
id: z.string(),
name: z.string(),
link: z.string(),
createdAt: z.string(),
updatedAt: z.string().nullable().optional(),
});

const CreatePartnerSchema = PartnerSchema.omit({
id: true,
createdAt: true,
updatedAt: true,
});

export { PartnerSchema, CreatePartnerSchema };
Empty file.
Empty file.
Empty file added src/prisma/hooks/user/index.ts
Empty file.
Empty file.
34 changes: 17 additions & 17 deletions src/shelter/ShelterSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class ShelterSearch {
) {
this.prismaService = prismaService;
this.formProps = { ...props };
this.getQuery = this.getQuery.bind(this);
}

priority(supplyIds: string[] = []): Prisma.ShelterWhereInput {
Expand Down Expand Up @@ -102,23 +103,20 @@ class ShelterSearch {
};
}

get search(): Prisma.ShelterWhereInput[] {
if (!this.formProps.search) return [];
async getSearch(): Promise<Prisma.ShelterWhereInput> {
if (!this.formProps.search) return {};

return [
{
address: {
contains: this.formProps.search,
mode: 'insensitive',
},
},
{
name: {
contains: this.formProps.search,
mode: 'insensitive',
},
const search = `${this.formProps.search.toLowerCase()}`;

const results = await this.prismaService.$queryRaw<{ id: string }[]>(
Prisma.sql`SELECT id FROM shelters WHERE lower(unaccent(address)) LIKE '%' || unaccent(${search}) || '%' OR lower(unaccent(name)) LIKE '%' || unaccent(${search}) || '%';`,
);

return {
id: {
in: results.map((r) => r.id),
},
];
};
}

get cities(): Prisma.ShelterWhereInput {
Expand Down Expand Up @@ -150,13 +148,15 @@ class ShelterSearch {
};
}

get query(): Prisma.ShelterWhereInput {
async getQuery(): Promise<Prisma.ShelterWhereInput> {
if (Object.keys(this.formProps).length === 0) return {};

const search = await this.getSearch();
const queryData = {
AND: [
this.cities,
this.geolocation,
{ OR: this.search },
search,
{ OR: this.shelterStatus },
this.priority(this.formProps.supplyIds),
this.supplyCategoryIds(this.formProps.priority),
Expand Down
Loading

0 comments on commit 451e986

Please sign in to comment.