Skip to content

✨ Result Status Helpers #176

@danielmackay

Description

@danielmackay

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions