From aa24bae84cbb4e3c36b9d8790244deaa8cbad204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Chevalier?= Date: Thu, 4 May 2023 15:16:10 +0200 Subject: [PATCH] adding usecase --- .../ad/domain/usecases/create-ad.usecase.ts | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/modules/ad/domain/usecases/create-ad.usecase.ts diff --git a/src/modules/ad/domain/usecases/create-ad.usecase.ts b/src/modules/ad/domain/usecases/create-ad.usecase.ts new file mode 100644 index 0000000..bf2d3d3 --- /dev/null +++ b/src/modules/ad/domain/usecases/create-ad.usecase.ts @@ -0,0 +1,45 @@ +import { Mapper } from '@automapper/core'; +import { InjectMapper } from '@automapper/nestjs'; +import { CommandHandler } from '@nestjs/cqrs'; +import { Messager } from '../../adapters/secondaries/messager'; +import { AdsRepository } from '../../adapters/secondaries/ads.repository'; +import { CreateAdCommand } from '../../commands/create-ad.command'; +import { CreateAdRequest } from '../dtos/create-ad.request'; +import { Ad } from '../entities/ad'; + +@CommandHandler(CreateAdCommand) +export class CreateAdUseCase { + constructor( + private readonly _repository: AdsRepository, + private readonly _messager: Messager, + @InjectMapper() private readonly _mapper: Mapper, + ) {} + + async execute(command: CreateAdCommand): Promise { + const entity = this._mapper.map( + command.createAdRequest, + CreateAdRequest, + Ad, + ); + + try { + const ad = await this._repository.create(entity); + this._messager.publish('ad.create', JSON.stringify(ad)); + this._messager.publish('logging.ad.create.info', JSON.stringify(ad)); + return ad; + } catch (error) { + let key = 'logging.ad.create.crit'; + if (error.message.includes('Already exists')) { + key = 'logging.ad.create.warning'; + } + this._messager.publish( + key, + JSON.stringify({ + command, + error, + }), + ); + throw error; + } + } +}