import { AggregateID, IdResponse, RpcExceptionCode, RpcValidationPipe, } from '@mobicoop/ddd-library'; import { Controller, UsePipes } from '@nestjs/common'; import { CommandBus } from '@nestjs/cqrs'; import { GrpcMethod, RpcException } from '@nestjs/microservices'; import { UsernameAlreadyExistsException } from '@modules/authentication/core/domain/authentication.errors'; import { AddUsernameRequestDto } from './dtos/add-username.request.dto'; import { AddUsernameCommand } from '@modules/authentication/core/application/commands/add-username/add-username.command'; @UsePipes( new RpcValidationPipe({ whitelist: true, forbidUnknownValues: false, }), ) @Controller() export class AddUsernameGrpcController { constructor(private readonly commandBus: CommandBus) {} @GrpcMethod('AuthenticationService', 'AddUsername') async addUsername(data: AddUsernameRequestDto): Promise { try { const aggregateID: AggregateID = await this.commandBus.execute( new AddUsernameCommand({ userId: data.userId, username: { name: data.name, type: data.type, }, }), ); return new IdResponse(aggregateID); } catch (error: any) { if (error instanceof UsernameAlreadyExistsException) throw new RpcException({ code: RpcExceptionCode.ALREADY_EXISTS, message: error.message, }); throw new RpcException({ code: RpcExceptionCode.UNKNOWN, message: error.message, }); } } }