Refactor email template handling and error management
- Updated EmailTemplateDto to allow mutable Body and Subject properties. - Implemented IRequest interface in UpdateEmailTemplateCommand for MediatR. - Enhanced error handling in EmailTemplateController with NotFoundException. - Introduced UpdateEmailTemplateCommandHandler for processing update commands. - Added NotFoundException class for improved error handling.
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
using DigitalData.Core.Abstractions.Infrastructure;
|
||||
using EnvelopeGenerator.Application.DTOs;
|
||||
using EnvelopeGenerator.Application.Exceptions;
|
||||
using EnvelopeGenerator.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace EnvelopeGenerator.Application.EmailTemplates.Commands.Update;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class UpdateEmailTemplateCommandHandler : IRequestHandler<UpdateEmailTemplateCommand>
|
||||
{
|
||||
private readonly IRepository<EmailTemplate> _repository;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="repository"></param>
|
||||
public UpdateEmailTemplateCommandHandler(IRepository<EmailTemplate> repository)
|
||||
{
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task Handle(UpdateEmailTemplateCommand request, CancellationToken cancel)
|
||||
{
|
||||
var temp = (request.EmailTemplateQuery?.Id is int id
|
||||
? await _repository.ReadOrDefaultAsync<EmailTemplateDto>(t => t.Id == id, single: false, cancel)
|
||||
: request!.EmailTemplateQuery!.Type is Common.Constants.EmailTemplateType type
|
||||
? await _repository.ReadOrDefaultAsync<EmailTemplateDto>(t => t.Name == type.ToString(), single: false, cancel)
|
||||
: throw new InvalidOperationException("Both id and type is null. Id: " + request.EmailTemplateQuery.Id + ". Type: " + request.EmailTemplateQuery.Type.ToString())) ?? throw new NotFoundException();
|
||||
|
||||
if(request.Body is not null)
|
||||
temp.Body = request.Body;
|
||||
|
||||
if (request.Subject is not null)
|
||||
temp.Subject = request.Subject;
|
||||
|
||||
await _repository.UpdateAsync(temp, t => t.Id == temp.Id, cancel);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user