Introduced `GetOrCreateCommandHandler` to handle `GetOrCreateCommand` requests. The handler checks if an `Endpoint` with the specified `Uri` exists in the repository and returns it if found. If not, it creates a new `Endpoint`, saves it, and returns the newly created object. Added necessary `using` directives for repository abstraction and Entity Framework Core functionality.
29 lines
835 B
C#
29 lines
835 B
C#
using DigitalData.Core.Abstraction.Application.Repository;
|
|
using MediatR;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using ReC.Domain.Entities;
|
|
|
|
namespace ReC.Application.Endpoints.Commands;
|
|
|
|
public class GetOrCreateCommand : IRequest<Endpoint>
|
|
{
|
|
public string Uri { get; init; } = null!;
|
|
}
|
|
|
|
public class GetOrCreateCommandHandler(IRepository<Endpoint> repo) : IRequestHandler<GetOrCreateCommand, Endpoint>
|
|
{
|
|
public async Task<Endpoint> Handle(GetOrCreateCommand request, CancellationToken cancel)
|
|
{
|
|
var endpoint = await repo.Where(e => e.Uri == request.Uri).FirstOrDefaultAsync(cancel);
|
|
|
|
if (endpoint is not null)
|
|
return endpoint;
|
|
|
|
endpoint = new Endpoint
|
|
{
|
|
Uri = request.Uri
|
|
};
|
|
await repo.CreateAsync(endpoint, cancel);
|
|
return endpoint;
|
|
}
|
|
} |