import { Mapper } from '@automapper/core'; import { InjectMapper } from '@automapper/nestjs'; import { BadRequestException, Body, ConflictException, Controller, NotFoundException, } from '@nestjs/common'; import { CommandBus, QueryBus } from '@nestjs/cqrs'; import { GrpcMethod, RpcException } from '@nestjs/microservices'; import { DatabaseException } from 'src/modules/database/src/exceptions/DatabaseException'; import { CreateUserCommand } from '../../commands/create-user.command'; import { UpdateUserCommand } from '../../commands/update-user.command'; import { CreateUserRequest } from '../../domain/dto/create-user.request'; import { FindUserByUuidRequest } from '../../domain/dto/find-user-by-uuid.request'; import { UpdateUserRequest } from '../../domain/dto/update-user.request'; import { User } from '../../domain/entities/user'; import { FindUserByUuidQuery } from '../../queries/find-user-by-uuid.query'; import { UserPresenter } from './user.presenter'; @Controller() export class UsersController { constructor( private readonly _commandBus: CommandBus, private readonly _queryBus: QueryBus, @InjectMapper() private readonly _mapper: Mapper, ) {} @GrpcMethod('UsersService', 'FindOneByUuid') async findOneByUuid(data: FindUserByUuidRequest): Promise { const user = await this._queryBus.execute( new FindUserByUuidQuery(data.uuid), ); if (user) { return this._mapper.map(user, User, UserPresenter); } throw new RpcException({ code: 5, message: 'User not found', }); } @GrpcMethod('UsersService', 'Create') async createUser(data: CreateUserRequest): Promise { try { const user = await this._commandBus.execute(new CreateUserCommand(data)); return this._mapper.map(user, User, UserPresenter); } catch (e) { if (e instanceof DatabaseException) { if (e.message.includes('Already exists')) { throw new RpcException({ code: 6, message: 'User already exists', }); } } throw new RpcException({}); } } @GrpcMethod('UsersService', 'Update') async updateUser(data: UpdateUserRequest): Promise { try { const user = await this._commandBus.execute(new UpdateUserCommand(data)); return this._mapper.map(user, User, UserPresenter); } catch (e) { if (e instanceof DatabaseException) { if (e.message.includes('not found')) { throw new RpcException({ code: 5, message: 'User not found', }); } } throw new RpcException({}); } } }