Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created July 31, 2023 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/c209274f6bfcc7436d8f463f8ace554a to your computer and use it in GitHub Desktop.
Save dj-nitehawk/c209274f6bfcc7436d8f463f8ace554a to your computer and use it in GitHub Desktop.
FastEndpoints usage with Ardalis.Result package
using Ardalis.Result;
using FastEndpoints;
using FastEndpoints.Swagger;
var bld = WebApplication.CreateBuilder();
bld.Services
.AddFastEndpoints()
.SwaggerDocument();
var app = bld.Build();
app.UseAuthorization()
.UseFastEndpoints()
.UseSwaggerGen();
app.Run();
sealed class Request
{
public bool IsHappyPath { get; set; }
}
sealed class Response
{
public string Message { get; set; }
}
sealed class TestEndpoint : Endpoint<Request, Response>
{
public override void Configure()
{
Get("test/{IsHappyPath}");
AllowAnonymous();
}
public override async Task HandleAsync(Request r, CancellationToken c)
{
var result = HelloService.SayHello(r.IsHappyPath);
await this.SendResponse(result, r => new Response
{
Message = r.Value
});
}
}
sealed class HelloService
{
public static Result<string> SayHello(bool isHappyPath)
{
if (!isHappyPath)
{
return Result<string>.Invalid(new List<ValidationError>
{
new ValidationError
{
Identifier = nameof(Request.IsHappyPath),
ErrorMessage = "I am unhappy!"
}
});
}
return Result<string>.Success("hello world...");
}
}
static class ArdalisResultsExtensions
{
public static async Task SendResponse<TResult, TResponse>(this IEndpoint ep, TResult result, Func<TResult, TResponse> mapper) where TResult : Ardalis.Result.IResult
{
switch (result.Status)
{
case ResultStatus.Ok:
await ep.HttpContext.Response.SendAsync(mapper(result));
break;
case ResultStatus.Invalid:
result.ValidationErrors.ForEach(e =>
ep.ValidationFailures.Add(new(e.Identifier, e.ErrorMessage)));
await ep.HttpContext.Response.SendErrorsAsync(ep.ValidationFailures);
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment