adding usecase

This commit is contained in:
Grégoire Chevalier 2023-05-04 15:16:10 +02:00
parent d17a3b9867
commit aa24bae84c
1 changed files with 45 additions and 0 deletions

View File

@ -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<Ad> {
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;
}
}
}