proteje rotas com JwtAuthGuard e documenta endpoints com Swagger

This commit is contained in:
unknown
2025-03-28 19:46:44 -03:00
parent 36aea127c1
commit 5e4ef04b4a
20 changed files with 372 additions and 66 deletions

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"compile-hero.disable-compile-files-on-did-save-code": false
}

26
package-lock.json generated
View File

@@ -26,6 +26,8 @@
"@types/estree": "^1.0.7", "@types/estree": "^1.0.7",
"aws-sdk": "^2.1692.0", "aws-sdk": "^2.1692.0",
"axios": "^1.8.4", "axios": "^1.8.4",
"class-transformer": "^0.5.1",
"class-validator": "^0.6.8",
"fs": "0.0.1-security", "fs": "0.0.1-security",
"guid-typescript": "^1.0.9", "guid-typescript": "^1.0.9",
"https": "^1.0.0", "https": "^1.0.0",
@@ -3997,6 +3999,12 @@
"integrity": "sha512-uc2Vix1frTfnuzxxu1Hp4ktSvM3QaI4oXl4ZUqL1wjTu/BGki9TrCWoqLTg/drR1KwAEarXuRFCG2Svr1GxPFw==", "integrity": "sha512-uc2Vix1frTfnuzxxu1Hp4ktSvM3QaI4oXl4ZUqL1wjTu/BGki9TrCWoqLTg/drR1KwAEarXuRFCG2Svr1GxPFw==",
"dev": true "dev": true
}, },
"node_modules/class-transformer": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/class-transformer/-/class-transformer-0.5.1.tgz",
"integrity": "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==",
"license": "MIT"
},
"node_modules/class-utils": { "node_modules/class-utils": {
"version": "0.3.6", "version": "0.3.6",
"resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz",
@@ -4024,6 +4032,15 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/class-validator": {
"version": "0.6.8",
"resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.6.8.tgz",
"integrity": "sha512-+G8KRwyk3J1pp1tHoIUkeH9/7GPfQLOZxfpiGXVQo0scGeB93IBlAm6SZ4Cur6mBEqL1lEOwdenPedIE/Rj9ew==",
"license": "MIT",
"dependencies": {
"validator": ">=5.0.0"
}
},
"node_modules/cli-cursor": { "node_modules/cli-cursor": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz",
@@ -11775,6 +11792,15 @@
"spdx-expression-parse": "^3.0.0" "spdx-expression-parse": "^3.0.0"
} }
}, },
"node_modules/validator": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/validator/-/validator-5.7.0.tgz",
"integrity": "sha512-kHes0AATXms5NVgbJ4aDELR91O7+X+cxAS9d6I2z49MBhcAw6DYW4UCI8qv9NkL4+Mgx8jklt7gkCht+UHaZ+g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/vary": { "node_modules/vary": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",

View File

@@ -37,6 +37,8 @@
"@types/estree": "^1.0.7", "@types/estree": "^1.0.7",
"aws-sdk": "^2.1692.0", "aws-sdk": "^2.1692.0",
"axios": "^1.8.4", "axios": "^1.8.4",
"class-transformer": "^0.5.1",
"class-validator": "^0.6.8",
"fs": "0.0.1-security", "fs": "0.0.1-security",
"guid-typescript": "^1.0.9", "guid-typescript": "^1.0.9",
"https": "^1.0.0", "https": "^1.0.0",

View File

@@ -1,5 +1,3 @@
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { import {
Body, Body,
Controller, Controller,
@@ -9,37 +7,47 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service'; import { UsersService } from '../users/users.service';
import { LoginDto } from '../auth/dto/login.dto';
import { ResultModel } from 'src/core/models/result.model'; import { ResultModel } from 'src/core/models/result.model';
import { LoginDto } from '../dto/login.dto'; import { ApiBody, ApiOkResponse, ApiUnauthorizedResponse } from '@nestjs/swagger';
@Controller('api/v1/auth') @Controller('api/v1/auth')
export class AuthController { export class AuthController {
constructor( constructor(
private usersService: UsersService, private readonly usersService: UsersService,
private authService: AuthService, private readonly authService: AuthService,
) { } ) {}
@Post('login') @Post('login')
async login(@Body() model: LoginDto): Promise<any> { @ApiBody({ type: LoginDto })
const user = await this.usersService.authenticate({ @ApiOkResponse({ description: 'Login realizado com sucesso' })
userName: model.username, @ApiUnauthorizedResponse({ description: 'Usuário ou senha inválidos' })
password: model.password, async login(@Body() model: LoginDto): Promise<any> {
}); const result = await this.usersService.authenticate({
userName: model.username,
if (!user) password: model.password,
throw new HttpException( });
new ResultModel(false, 'Usuário ou senha inválidos.', null, null),
HttpStatus.UNAUTHORIZED, console.log('Resultado da autenticação:', result);
);
if (!result.success) {
throw new HttpException(
new ResultModel(false, result.error, null, result.error),
HttpStatus.UNAUTHORIZED,
);
}
const user = result.data;
const token = await this.authService.createToken( const token = await this.authService.createToken(
user.id, user.id,
user.sellerId, user.sellerId,
user.name, user.name,
user.email, user.email,
user.storeId user.storeId,
); );
return { return {
id: user.id, id: user.id,
sellerId: user.sellerId, sellerId: user.sellerId,
@@ -50,4 +58,4 @@ async login(@Body() model: LoginDto): Promise<any> {
token: token, token: token,
}; };
} }
} }

View File

@@ -5,7 +5,7 @@ import { AuthService } from './auth.service';
import { JwtModule, JwtService } from '@nestjs/jwt'; import { JwtModule, JwtService } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport'; import { PassportModule } from '@nestjs/passport';
import { UsersModule } from '../users/users.module'; import { UsersModule } from '../users/users.module';
import { JwtStrategy } from '../strategies/jwt-strategy';
@Module({ @Module({
imports: [ imports: [
UsersModule, UsersModule,
@@ -20,7 +20,7 @@ import { UsersModule } from '../users/users.module';
}), }),
], ],
controllers: [AuthController], controllers: [AuthController],
providers: [AuthService], providers: [AuthService,JwtStrategy],
exports: [AuthService], exports: [AuthService],
}) })
export class AuthModule {} export class AuthModule {}

View File

@@ -6,6 +6,7 @@ import { UsersService } from '../users/users.service';
import { JwtPayload } from '../models/jwt-payload.model'; import { JwtPayload } from '../models/jwt-payload.model';
@Injectable() @Injectable()
export class AuthService { export class AuthService {
constructor( constructor(
@@ -25,8 +26,7 @@ export class AuthService {
return this.jwtService.sign(user, options); return this.jwtService.sign(user, options);
} }
async validateUser(payload: JwtPayload): Promise<any> { async validateUser(payload: JwtPayload): Promise<JwtPayload | null> {
//return await this.accountService.findOneByUsername(payload.username);
return payload; return payload;
} }
} }

View File

@@ -0,0 +1,7 @@
export class AuthenticateUserCommand {
constructor(
public readonly username: string,
public readonly password: string,
) {}
}

View File

@@ -1,23 +1,29 @@
import { Injectable, ForbiddenException } from '@nestjs/common'; import { Injectable, ForbiddenException } from '@nestjs/common';
import { UserRepository } from '../users/UserRepository'; import { UserRepository } from '../users/UserRepository';
import { AuthenticateUserCommand } from './authenticate-user.command';
import { Result } from '../models/result';
@Injectable() @Injectable()
export class AuthenticateUserService { export class AuthenticateUserService {
constructor(private readonly userRepository: UserRepository) {} constructor(private readonly userRepository: UserRepository) {}
async execute(username: string, password: string) { async execute(command: AuthenticateUserCommand): Promise<Result<any>> {
const { username, password } = command;
const user = await this.userRepository.findByUsernameAndPassword(username, password); const user = await this.userRepository.findByUsernameAndPassword(username, password);
if (!user) return null; if (!user) {
return Result.fail('Usuário ou senha inválidos');
}
if (user.dataDesligamento !== null) { if (user.dataDesligamento !== null) {
throw new ForbiddenException('Usuário desligado da empresa, login não permitido!'); return Result.fail('Usuário desligado da empresa, login não permitido!');
} }
if (user.situacao === 'I') { if (user.situacao === 'I') {
throw new ForbiddenException('Usuário inativo, login não permitido!'); return Result.fail('Usuário inativo, login não permitido!');
} }
return user; return Result.ok(user);
} }
} }

82
src/auth/auth/dist/auth.service.js vendored Normal file
View File

@@ -0,0 +1,82 @@
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.AuthService = void 0;
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
var common_1 = require("@nestjs/common");
var AuthService = /** @class */ (function () {
function AuthService(usersService, jwtService) {
this.usersService = usersService;
this.jwtService = jwtService;
}
AuthService.prototype.createToken = function (id, sellerId, username, email, storeId) {
return __awaiter(this, void 0, void 0, function () {
var user, options;
return __generator(this, function (_a) {
user = {
id: id,
sellerId: sellerId,
storeId: storeId,
username: username,
email: email
};
options = { expiresIn: '8h' };
return [2 /*return*/, this.jwtService.sign(user, options)];
});
});
};
AuthService.prototype.validateUser = function (payload) {
return __awaiter(this, void 0, Promise, function () {
return __generator(this, function (_a) {
return [2 /*return*/, payload];
});
});
};
AuthService = __decorate([
common_1.Injectable()
], AuthService);
return AuthService;
}());
exports.AuthService = AuthService;

View File

@@ -0,0 +1,11 @@
import { IsString, IsNotEmpty } from 'class-validator';
export class LoginDto {
@IsString()
@IsNotEmpty()
username: string;
@IsString()
@IsNotEmpty()
password: string;
}

46
src/auth/doc/doc.txt Normal file
View File

@@ -0,0 +1,46 @@
Controller
↓ recebe LoginDto
UsersService
↓ monta o AuthenticateUserCommand
AuthenticateUserService
↓ executa regras de negócio
UserRepository
↓ executa query no banco
Result<User>
← resposta encapsulada
1. LoginController
Entrada da requisição HTTP (POST /auth/login)
Recebe LoginDto com email e password
Encaminha para o UsersService
2. UsersService
Cria e valida o comando AuthenticateUserCommand
Chama o serviço de autenticação de domínio (AuthenticateUserService)
3. AuthenticateUserService
Lógica de negócio da autenticação:
Busca usuário pelo e-mail
Verifica se o usuário está ativo
Valida a senha com hash
Retorna Result<User>
4. UserRepository
Camada de persistência (interface com o banco de dados)
Executa a query findByEmail(email: string)
5. Result<T>
Objeto genérico de retorno que encapsula:
Sucesso (success = true, com data: User)
Falha (success = false, com error: string)

View File

@@ -1,5 +0,0 @@
export class LoginDto {
username: string;
password: string;
}

View File

@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

View File

@@ -10,7 +10,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) { constructor(private readonly authService: AuthService) {
super({ super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKeyProvider: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9', //secretOrKey secretOrKey: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9',
}); });
} }

View File

@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm'; // <-- importe aqui import { TypeOrmModule } from '@nestjs/typeorm'; // <-- importe aqui
import { UsersService } from './users.service'; import { UsersService } from './users.service';
import { UserRepository } from './UserRepository'; import { UserRepository } from './UserRepository';
import { AuthenticateUserService } from '../auth/authenticate-user.service'; import { AuthenticateUserService } from '../auth/authenticate-user.service';
import { ResetPasswordService } from './reset-password.service'; import { ResetPasswordService } from './reset-password.service';
import { ChangePasswordService } from './change-password.service'; import { ChangePasswordService } from './change-password.service';

View File

@@ -2,6 +2,8 @@ import { Injectable } from '@nestjs/common';
import { AuthenticateUserService } from '../auth/authenticate-user.service'; import { AuthenticateUserService } from '../auth/authenticate-user.service';
import { ResetPasswordService } from './reset-password.service'; import { ResetPasswordService } from './reset-password.service';
import { ChangePasswordService } from './change-password.service'; import { ChangePasswordService } from './change-password.service';
import { AuthenticateUserCommand } from '../auth/authenticate-user.command';
@Injectable() @Injectable()
@@ -13,9 +15,9 @@ export class UsersService {
) {} ) {}
async authenticate(user: { userName: string; password: string }) { async authenticate(user: { userName: string; password: string }) {
return this.authenticateUserService.execute(user.userName, user.password); const command = new AuthenticateUserCommand(user.userName, user.password);
return this.authenticateUserService.execute(command);
} }
async resetPassword(user: { document: string; email: string }) { async resetPassword(user: { document: string; email: string }) {
return this.resetPasswordService.execute(user.document, user.email); return this.resetPasswordService.execute(user.document, user.email);
} }

View File

@@ -1,6 +1,7 @@
import { Controller, Get, Param } from '@nestjs/common'; import { Controller, Get, Param,UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiParam } from '@nestjs/swagger'; import { ApiTags, ApiOperation, ApiParam, ApiBearerAuth } from '@nestjs/swagger';
import { DataConsultService } from './data-consult.service'; import { DataConsultService } from './data-consult.service';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard'
@ApiTags('DataConsult') @ApiTags('DataConsult')
@Controller('api/v1/data-consult') @Controller('api/v1/data-consult')
@@ -8,24 +9,32 @@ export class DataConsultController {
constructor(private readonly dataConsultService: DataConsultService) {} constructor(private readonly dataConsultService: DataConsultService) {}
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Get('stores') @Get('stores')
@ApiOperation({ summary: 'Lista todas as lojas' }) @ApiOperation({ summary: 'Lista todas as lojas' })
async stores() { async stores() {
return this.dataConsultService.stores(); return this.dataConsultService.stores();
} }
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Get('sellers') @Get('sellers')
@ApiOperation({ summary: 'Lista todos os vendedores' }) @ApiOperation({ summary: 'Lista todos os vendedores' })
async sellers() { async sellers() {
return this.dataConsultService.sellers(); return this.dataConsultService.sellers();
} }
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Get('billings') @Get('billings')
@ApiOperation({ summary: 'Retorna informações de faturamento' }) @ApiOperation({ summary: 'Retorna informações de faturamento' })
async billings() { async billings() {
return this.dataConsultService.billings(); return this.dataConsultService.billings();
} }
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Get('customers/:filter') @Get('customers/:filter')
@ApiOperation({ summary: 'Filtra clientes pelo parâmetro fornecido' }) @ApiOperation({ summary: 'Filtra clientes pelo parâmetro fornecido' })
@ApiParam({ name: 'filter', description: 'Filtro de busca para clientes' }) @ApiParam({ name: 'filter', description: 'Filtro de busca para clientes' })

View File

@@ -0,0 +1,79 @@
"use strict";
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
/*
https://docs.nestjs.com/controllers#controllers
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
exports.__esModule = true;
exports.LogisticController = void 0;
var common_1 = require("@nestjs/common");
var jwt_auth_guard_1 = require("src/auth/guards/jwt-auth.guard"); // ajuste o caminho se necessário
var swagger_1 = require("@nestjs/swagger");
var LogisticController = /** @class */ (function () {
function LogisticController(logisticService) {
this.logisticService = logisticService;
}
LogisticController.prototype.getExpedicao = function () {
return this.logisticService.getExpedicao();
};
LogisticController.prototype.getEmployee = function () {
return this.logisticService.getEmployee();
};
LogisticController.prototype.getDelivery = function (placa) {
return this.logisticService.getDeliveries(placa);
};
LogisticController.prototype.getStatusCar = function (placa) {
return this.logisticService.getStatusCar(placa);
};
LogisticController.prototype.createOutCar = function (data) {
return this.logisticService.createCarOut(data);
};
LogisticController.prototype.createinCar = function (data) {
return this.logisticService.createCarIn(data);
};
__decorate([
common_1.Get('expedicao'),
swagger_1.ApiOperation({ summary: 'Retorna informações de expedição' })
], LogisticController.prototype, "getExpedicao");
__decorate([
common_1.Get('employee'),
swagger_1.ApiOperation({ summary: 'Retorna lista de funcionários' })
], LogisticController.prototype, "getEmployee");
__decorate([
common_1.Get('deliveries/:placa'),
swagger_1.ApiOperation({ summary: 'Retorna entregas por placa' }),
__param(0, common_1.Param('placa'))
], LogisticController.prototype, "getDelivery");
__decorate([
common_1.Get('status-car/:placa'),
swagger_1.ApiOperation({ summary: 'Retorna status do veículo por placa' }),
__param(0, common_1.Param('placa'))
], LogisticController.prototype, "getStatusCar");
__decorate([
common_1.Post('create'),
swagger_1.ApiOperation({ summary: 'Registra saída de veículo' }),
__param(0, common_1.Body())
], LogisticController.prototype, "createOutCar");
__decorate([
common_1.Post('return-car'),
swagger_1.ApiOperation({ summary: 'Registra retorno de veículo' }),
__param(0, common_1.Body())
], LogisticController.prototype, "createinCar");
LogisticController = __decorate([
swagger_1.ApiTags('Logística'),
swagger_1.ApiBearerAuth(),
common_1.UseGuards(jwt_auth_guard_1.JwtAuthGuard),
common_1.Controller('api/v1/logistic')
], LogisticController);
return LogisticController;
}());
exports.LogisticController = LogisticController;

View File

@@ -4,48 +4,62 @@
https://docs.nestjs.com/controllers#controllers https://docs.nestjs.com/controllers#controllers
*/ */
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { LogisticService } from './logistic.service'; import { LogisticService } from './logistic.service';
import { CarOutDelivery } from '../core/models/car-out-delivery.model'; import { CarOutDelivery } from '../core/models/car-out-delivery.model';
import { CarInDelivery } from '../core/models/car-in-delivery.model'; import { CarInDelivery } from '../core/models/car-in-delivery.model';
import {
Body,
Controller,
Get,
Param,
Post,
UseGuards
} from '@nestjs/common';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard'; // ajuste o caminho se necessário
import { ApiBearerAuth, ApiTags, ApiOperation } from '@nestjs/swagger';
@Controller('api/v1/logistic') @ApiTags('Logística')
export class LogisticController { @ApiBearerAuth()
@UseGuards(JwtAuthGuard)
constructor( private readonly logisticService: LogisticService) {} @Controller('api/v1/logistic')
export class LogisticController {
constructor(private readonly logisticService: LogisticService) {}
@Get('expedicao') @Get('expedicao')
@ApiOperation({ summary: 'Retorna informações de expedição' })
getExpedicao() { getExpedicao() {
try { return this.logisticService.getExpedicao();
return this.logisticService.getExpedicao();
} catch (err) {
console.log(err);
}
} }
@Get('employee') @Get('employee')
@ApiOperation({ summary: 'Retorna lista de funcionários' })
getEmployee() { getEmployee() {
return this.logisticService.getEmployee(); return this.logisticService.getEmployee();
} }
@Get('deliveries/:placa') @Get('deliveries/:placa')
@ApiOperation({ summary: 'Retorna entregas por placa' })
getDelivery(@Param('placa') placa: string) { getDelivery(@Param('placa') placa: string) {
return this.logisticService.getDeliveries(placa); return this.logisticService.getDeliveries(placa);
} }
@Get('status-car/:placa') @Get('status-car/:placa')
@ApiOperation({ summary: 'Retorna status do veículo por placa' })
getStatusCar(@Param('placa') placa: string) { getStatusCar(@Param('placa') placa: string) {
return this.logisticService.getStatusCar(placa); return this.logisticService.getStatusCar(placa);
} }
@Post('create') @Post('create')
@ApiOperation({ summary: 'Registra saída de veículo' })
createOutCar(@Body() data: CarOutDelivery) { createOutCar(@Body() data: CarOutDelivery) {
return this.logisticService.createCarOut(data); return this.logisticService.createCarOut(data);
} }
@Post('return-car') @Post('return-car')
@ApiOperation({ summary: 'Registra retorno de veículo' })
createinCar(@Body() data: CarInDelivery) { createinCar(@Body() data: CarInDelivery) {
return this.logisticService.createCarIn(data); return this.logisticService.createCarIn(data);
} }
}
}

View File

@@ -1,11 +1,20 @@
/* eslint-disable prettier/prettier */
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
app.enableCors({ app.enableCors({
origin: '*', origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
@@ -23,6 +32,7 @@ async function bootstrap() {
const document = SwaggerModule.createDocument(app, config); const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document); SwaggerModule.setup('docs', app, document);
await app.listen(9009);
await app.listen(9001);
} }
bootstrap(); bootstrap();