Ardalis Result<T> carried incoherent success sub-statuses and a clunky generic converter; ErrorOr models success-or-errors cleanly. - Application: all commands/queries/handlers now return ErrorOr<T> (non-generic Result -> ErrorOr<Success>); errors via Error.NotFound/ Conflict/Validation/Unauthorized/Failure; success via value or new Success() - Drop ResultExtensions.As<>(): error propagation is now just return .Errors - Rewrite HTTP mapping (ErrorOrHttpExtensions) off Error.Type; success maps to 200 (value) or 204 (Success); Created still built in the endpoints - Endpoints/gateway middleware: !IsSuccess -> IsError - Swap Ardalis.Result package for ErrorOr 2.1.1 (remove unused ref from Worker) Build: 0 warnings, 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
40 lines
1.6 KiB
C#
40 lines
1.6 KiB
C#
using ErrorOr;
|
|
using Mediator;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
using Musify.Application.Contracts;
|
|
using Musify.Application.Users.Commands;
|
|
using Musify.Application.Users.Responses;
|
|
|
|
namespace Musify.Application.Users.Handlers
|
|
{
|
|
public class CreateUserCommandHandler(IDatabase database, ILogger<CreateUserCommandHandler> logger)
|
|
: ICommandHandler<CreateUserCommand, ErrorOr<UserApplicationResponse> >
|
|
{
|
|
public async ValueTask<ErrorOr<UserApplicationResponse>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var userExists = await database.Users.AnyAsync(u => u.Id == request.Id, cancellationToken);
|
|
if (userExists)
|
|
{
|
|
logger.LogInformation("User {UserId} already exists", request.Id);
|
|
return Error.Conflict(description: $"User {request.Id} already exists");
|
|
}
|
|
|
|
var newUser = CreateUserCommand.ToEntity(request);
|
|
|
|
try
|
|
{
|
|
await database.Users.AddAsync(newUser, cancellationToken);
|
|
await database.SaveChangesAsync(cancellationToken);
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
logger.LogError(exception, "Failed to create user {UserId}", request.Id);
|
|
return Error.Failure(description: $"Failed to create user {request.Id}");
|
|
}
|
|
|
|
logger.LogInformation("Created user {UserId}", newUser.Id);
|
|
return UserApplicationResponse.FromEntity(newUser);
|
|
}
|
|
}
|
|
} |