45 lines
1.5 KiB
C#
45 lines
1.5 KiB
C#
using AutoMapper;
|
|
using Chatbot.Api.Application.Commands;
|
|
using Chatbot.Api.Application.Events;
|
|
using Chatbot.Api.Domain.Entities;
|
|
using Chatbot.Api.Domain.Repositories;
|
|
using MediatR;
|
|
using Microsoft.Extensions.Logging;
|
|
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Chatbot.Api.Application.CommandHandlers
|
|
{
|
|
public class SaveChatMessageHandler : IRequestHandler<SaveChatMessage, ChatMessageSaved>
|
|
{
|
|
private readonly ILogger<SaveChatMessageHandler> _logger;
|
|
private readonly IMapper _mapper;
|
|
private readonly IChatRepository _chatRepository;
|
|
|
|
public SaveChatMessageHandler(ILogger<SaveChatMessageHandler> logger, IMapper mapper, IChatRepository chatRepository)
|
|
{
|
|
_logger = logger;
|
|
_mapper = mapper;
|
|
_chatRepository = chatRepository;
|
|
}
|
|
|
|
public async Task<ChatMessageSaved> Handle(SaveChatMessage request, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
var message = _mapper.Map<ChatMessage>(request);
|
|
await _chatRepository.Add(message);
|
|
|
|
return new ChatMessageSaved(true, null);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
var correlationIdMsg = $"CorrelationId: {request.Metadata.CorrelationId}";
|
|
_logger.LogError(ex, $"An unexpected error has occurred. {correlationIdMsg}");
|
|
return new ChatMessageSaved(false, $"{ex.Message} {correlationIdMsg}");
|
|
}
|
|
}
|
|
}
|
|
}
|