Skip to content

feat: Add request body validation with DTOs & Swagger docs to the routes #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
"@nestjs/swagger": "^7.3.1",
"@prisma/client": "^5.13.0",
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"date-fns": "^3.6.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.0",
Expand Down
10 changes: 10 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
const fastifyAdapter = new FastifyAdapter();
Expand All @@ -14,11 +15,20 @@ async function bootstrap() {
fastifyAdapter,
);

app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
}),
);

const config = new DocumentBuilder()
.setTitle('SOS - Rio Grande do Sul')
.setDescription('...')
.setVersion('1.0')
.addBearerAuth()
.build();

const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

Expand Down
14 changes: 14 additions & 0 deletions src/sessions/dtos/LoginSessionDTO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';

export class LoginSessionDTO {
@ApiProperty({ type: 'string', example: 'John' })
@IsNotEmpty()
@IsString()
readonly login = '';

@ApiProperty({ type: 'string', example: 'john123' })
@IsNotEmpty()
@IsString()
readonly password = '';
}
25 changes: 22 additions & 3 deletions src/sessions/sessions.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,19 @@ import {
Request,
UseGuards,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import {
ApiBadRequestResponse,
ApiBearerAuth,
ApiInternalServerErrorResponse,
ApiOkResponse,
ApiTags,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';

import { UserGuard } from '@/guards/user.guard';
import { ServerResponse } from '../utils';
import { SessionsService } from './sessions.service';
import { LoginSessionDTO } from './dtos/LoginSessionDTO';

@ApiTags('Sessões')
@Controller('sessions')
Expand All @@ -23,14 +31,17 @@ export class SessionsController {

constructor(private readonly sessionService: SessionsService) {}

@ApiBadRequestResponse()
@ApiInternalServerErrorResponse()
@ApiOkResponse()
@Post('')
async login(
@Body() body,
@Body() body: LoginSessionDTO,
@Headers('x-real-ip') ip: string,
@Headers('user-agent') userAgent: string,
) {
try {
const data = await this.sessionService.login({ ...body, ip, userAgent });
const data = await this.sessionService.login(body, ip, userAgent);
return new ServerResponse(200, 'Successfully logged in', data);
} catch (err: any) {
this.logger.error(`Failed to login ${err}`);
Expand All @@ -41,6 +52,10 @@ export class SessionsController {
}
}

@ApiBearerAuth()
@ApiUnauthorizedResponse()
@ApiInternalServerErrorResponse()
@ApiOkResponse()
@Get('')
@UseGuards(UserGuard)
async show(@Request() req) {
Expand All @@ -54,6 +69,10 @@ export class SessionsController {
}
}

@ApiBearerAuth()
@ApiUnauthorizedResponse()
@ApiInternalServerErrorResponse()
@ApiOkResponse()
@Delete('')
@UseGuards(UserGuard)
async delete(@Request() req) {
Expand Down
13 changes: 11 additions & 2 deletions src/sessions/sessions.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as bcrypt from 'bcrypt';

import { PrismaService } from '../prisma/prisma.service';
import { LoginSchema, TokenPayload } from './types';
import { LoginSessionDTO } from './dtos/LoginSessionDTO';

@Injectable()
export class SessionsService {
Expand All @@ -12,8 +13,16 @@ export class SessionsService {
private readonly jwtService: JwtService,
) {}

async login(body: any) {
const { login, password, ip, userAgent } = LoginSchema.parse(body);
async login(
body: LoginSessionDTO,
ipHeaders: string,
userAgentHeaders: string,
) {
const { login, password, ip, userAgent } = LoginSchema.parse({
...body,
ipHeaders,
userAgentHeaders,
});
const user = await this.prismaService.user.findUnique({
where: { login },
});
Expand Down
14 changes: 14 additions & 0 deletions src/shelter-managers/dtos/CreateShelterManagerDTO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';

export class CreateShelterManagerDTO {
@ApiProperty({ type: 'string', example: 'ID do Abrigo' })
@IsNotEmpty()
@IsString()
readonly shelterId = '';

@ApiProperty({ type: 'string', example: 'ID do Usuário' })
@IsNotEmpty()
@IsString()
readonly userId = '';
}
18 changes: 16 additions & 2 deletions src/shelter-managers/shelter-managers.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,22 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import {
ApiBadRequestResponse,
ApiBearerAuth,
ApiInternalServerErrorResponse,
ApiOkResponse,
ApiTags,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';

import { ShelterManagersService } from './shelter-managers.service';
import { ServerResponse } from '../utils';
import { AdminGuard } from '@/guards/admin.guard';
import { CreateShelterManagerDTO } from './dtos/CreateShelterManagerDTO';

@ApiTags('Admin de Abrigo')
@ApiInternalServerErrorResponse()
@Controller('shelter/managers')
export class ShelterManagersController {
private logger = new Logger(ShelterManagersController.name);
Expand All @@ -24,9 +33,13 @@ export class ShelterManagersController {
private readonly shelterManagerServices: ShelterManagersService,
) {}

@ApiBearerAuth()
@ApiUnauthorizedResponse()
@ApiBadRequestResponse()
@ApiOkResponse()
@Post('')
@UseGuards(AdminGuard)
async store(@Body() body) {
async store(@Body() body: CreateShelterManagerDTO) {
try {
await this.shelterManagerServices.store(body);
return new ServerResponse(200, 'Successfully added manager to shelter');
Expand All @@ -36,6 +49,7 @@ export class ShelterManagersController {
}
}

@ApiOkResponse()
@Get(':shelterId')
async index(
@Param('shelterId') shelterId: string,
Expand Down
4 changes: 2 additions & 2 deletions src/shelter-managers/shelter-managers.service.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { z } from 'zod';
import { Injectable } from '@nestjs/common';

import { PrismaService } from '../prisma/prisma.service';
import { CreateShelterManagerSchema } from './types';
import { CreateShelterManagerDTO } from './dtos/CreateShelterManagerDTO';

@Injectable()
export class ShelterManagersService {
constructor(private readonly prismaService: PrismaService) {}

async store(body: z.infer<typeof CreateShelterManagerSchema>) {
async store(body: CreateShelterManagerDTO) {
const { shelterId, userId } = CreateShelterManagerSchema.parse(body);
await this.prismaService.shelterManagers.create({
data: {
Expand Down
47 changes: 47 additions & 0 deletions src/shelter-supply/dtos/CreateShelterSupplyDTO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import {
IsEnum,
IsNotEmpty,
IsNumber,
IsOptional,
IsString,
Min,
} from 'class-validator';
import { SupplyPriority } from 'src/supply/types';

export class CreateShelterSupplyDTO {
constructor() {
this.priority = SupplyPriority.UnderControl;
}

@ApiProperty({ type: 'string', example: 'ID do Abrigo' })
@IsNotEmpty()
@IsString()
readonly shelterId = '';

@ApiProperty({ type: 'string', example: 'ID do Suprimento' })
@IsNotEmpty()
@IsString()
readonly supplyId = '';

@ApiProperty({
description: 'Prioridade de suprimento',
enum: SupplyPriority,
})
@IsNotEmpty()
@IsEnum(SupplyPriority)
@Transform((value) => Number(value.value))
readonly priority: SupplyPriority;

@ApiProperty({
required: false,
type: 'number',
example: 1,
})
@IsOptional()
@IsNumber()
@Min(1)
@Transform((value) => Number(value.value))
readonly quantity?: number;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

não deveria ser obrigatório? afinal estou criando um suprimento e estou dizendo que seu deve ser mínimo um

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eu apenas segui a lógica já implementada na aplicação, então nesse DTO a propriedade "quantity" deve ser opcional, como consta nos types

const ShelterSupplySchema = z.object({
id: z.string(),
shelterId: z.string(),
supplyId: z.string(),
priority: z.union([
z.literal(SupplyPriority.UnderControl),
z.literal(SupplyPriority.Remaining),
z.literal(SupplyPriority.Needing),
z.literal(SupplyPriority.Urgent),
]),
quantity: z.number().gt(0).nullable().optional(),
createdAt: z.string(),
updatedAt: z.string().nullable().optional(),
});
const CreateShelterSupplySchema = ShelterSupplySchema.pick({
shelterId: true,
supplyId: true,
priority: true,
quantity: true,
});

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfeito! Acredito que não era para ter esse 'estado' nos types mas como já é o formato antigo, tudo em ordem camarada

}
14 changes: 14 additions & 0 deletions src/shelter-supply/dtos/UpdateManyShelterSupplyDTO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { ArrayMinSize, IsArray, IsNotEmpty, IsString } from 'class-validator';

export class UpdateManyShelterSupplySchemaDTO {
@ApiProperty({
type: [String],
example: ['ID do Suprimento', 'ID do Suprimento 2'],
})
@IsArray()
@ArrayMinSize(1)
@IsNotEmpty()
@IsString({ each: true })
readonly ids!: string;
}
27 changes: 27 additions & 0 deletions src/shelter-supply/dtos/UpdateShelterSupplyDTO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsEnum, IsOptional, IsNumber, Min } from 'class-validator';
import { SupplyPriority } from 'src/supply/types';

export class UpdateShelterSupplyDTO {
@ApiProperty({
required: false,
description: 'Prioridade de suprimento',
enum: SupplyPriority,
})
@IsOptional()
@IsEnum(SupplyPriority)
@Transform((value) => Number(value.value))
readonly priority?: SupplyPriority;

@ApiProperty({
required: false,
type: 'number',
example: 1,
})
@IsOptional()
@IsNumber()
@Min(1)
@Transform((value) => Number(value.value))
readonly quantity?: number;
}
Loading