Result icon indicating copy to clipboard operation
Result copied to clipboard

✨ Result Status Helpers

Open danielmackay opened this issue 2 years ago • 0 comments

Pain

When checking the result status (for example a service called from a minimal API). The code seems more verbose that it could be.

For example:

app
  .MapPost("/",
      async Task<Results<Created, BadRequest<ValidationProblemDetails>, NotFound>> (
          [FromServices] ISender sender,
          [FromBody] CreateLeaveCommand command, CancellationToken ct) =>
      {
          var result = await sender.Send(command, ct);
          if (result.Status == ResultStatus.BadRequest) // 👈 here
              return TypedResults.BadRequest(result.ToValidationProblem());
  
          if (result.Status == ResultStatus.NotFound) // 👈 here
              return TypedResults.NotFound();
  
          return TypedResults.Created();
      })
  .WithName("CreateLeave");

Solution

Add helper fields to IResult so that the code is more concise. The result would look something like:

app
  .MapPost("/",
      async Task<Results<Created, BadRequest<ValidationProblemDetails>, NotFound>> (
          [FromServices] ISender sender,
          [FromBody] CreateLeaveCommand command, CancellationToken ct) =>
      {
          var result = await sender.Send(command, ct);
          if (result.IsInvalid) // 👈 here
              return TypedResults.BadRequest(result.ToValidationProblem());
  
          if (result.IsNotFound) // 👈 here
              return TypedResults.NotFound();
  
          return TypedResults.Created();
      })
  .WithName("CreateLeave");

The above reads much cleaner and removes unneeded code.

@ardalis:

  1. What do you think of the above?
  2. Would you be happy for me to create a PR for this?
  3. Do you think IResult is the best place to put this?

danielmackay avatar Apr 27 '24 06:04 danielmackay