diff --git a/EnvelopeGenerator.Application/Receivers/Commands/CreateReceiverCommand.cs b/EnvelopeGenerator.Application/Receivers/Commands/CreateReceiverCommand.cs index aa241bcf..434e0801 100644 --- a/EnvelopeGenerator.Application/Receivers/Commands/CreateReceiverCommand.cs +++ b/EnvelopeGenerator.Application/Receivers/Commands/CreateReceiverCommand.cs @@ -2,6 +2,7 @@ using EnvelopeGenerator.Domain.Entities; using MediatR; using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; using System.Security.Cryptography; using System.Text; @@ -12,7 +13,7 @@ namespace EnvelopeGenerator.Application.Receivers.Commands; /// /// [ApiExplorerSettings(IgnoreApi = true)] -public record CreateReceiverCommand : IRequest +public record CreateReceiverCommand : IRequest<(int Id, bool AlreadyExists)> { /// /// @@ -51,7 +52,7 @@ public record CreateReceiverCommand : IRequest /// /// /// -public class CreateReceiverCommandHandler : IRequestHandler +public class CreateReceiverCommandHandler : IRequestHandler { /// /// @@ -73,9 +74,17 @@ public class CreateReceiverCommandHandler : IRequestHandler /// /// - public async Task Handle(CreateReceiverCommand request, CancellationToken cancel) + public async Task<(int Id, bool AlreadyExists)> Handle(CreateReceiverCommand request, CancellationToken cancel) { - Receiver receiver = await _repo.CreateAsync(request, cancel); - return receiver.Id; + var receiver = await _repo.ReadOnly() + .Where(r => r.EmailAddress == request.EmailAddress) + .SingleOrDefaultAsync(cancel); + + var alreadyExists = receiver is not null; + + if (!alreadyExists) + receiver = await _repo.CreateAsync(request, cancel); + + return (receiver!.Id, alreadyExists); } } \ No newline at end of file diff --git a/EnvelopeGenerator.Tests.Application/HistoryTests.cs b/EnvelopeGenerator.Tests.Application/HistoryTests.cs index 132fd614..7554a1d7 100644 --- a/EnvelopeGenerator.Tests.Application/HistoryTests.cs +++ b/EnvelopeGenerator.Tests.Application/HistoryTests.cs @@ -64,8 +64,8 @@ public class HistoryTests .Select(async email => { var cmd = new CreateReceiverCommand { EmailAddress = email }; - var id = await Mediator.Send(cmd); - return (id, email); + var res = await Mediator.Send(cmd); + return (res.Id, email); }) ); _receivers.AddRange(receivers);