Skip to content

Instantly share code, notes, and snippets.

@DamianEdwards
Created February 17, 2022 17:14
Show Gist options
  • Save DamianEdwards/8e802997487978cbb2880bad8f82c3f0 to your computer and use it in GitHub Desktop.
Save DamianEdwards/8e802997487978cbb2880bad8f82c3f0 to your computer and use it in GitHub Desktop.
// Now
app.MapGet("/todos/{id}", async (int id, TodoDb db) =>
await db.Todos.FindAsync(id)
is Todo todo
? Results.Ok(todo)
: Results.NotFound())
.WithName("GetTodoById")
.Produces<Todo>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound);
// Using the MinimalApis.Extensions library
app.MapGet("/todos/{id}", async Task<Results<Ok<Todo>, NotFound>> (int id, IDbConnection db) =>
await db.QuerySingleOrDefaultAsync<Todo>("SELECT * FROM Todos WHERE Id = @id", new { id })
is Todo todo
? Results.Extensions.Ok(todo)
: Results.Extensions.NotFound())
.WithName("GetTodoById");
// Potential C# 11 discriminated union return?
app.MapGet("/todos/{id}", async union (int id, TodoDb db) =>
await db.Todos.FindAsync(id)
is Todo todo
? todo
: Results.NotFound())
.WithName("GetTodoById");
// Or maybe an inline explicitly defined union target type
app.MapGet("/todos/{id}", async (Todo|NotFound) (int id, TodoDb db) =>
await db.Todos.FindAsync(id)
is Todo todo
? todo
: Results.NotFound())
.WithName("GetTodoById");
// Or maybe a declared explicitly defined union target type
app.MapGet("/todos/{id}", async GetResult<Todo> (int id, TodoDb db) =>
await db.Todos.FindAsync(id)
is Todo todo
? todo
: Results.NotFound())
.WithName("GetTodoById");
enum struct GetResult<T> { Ok<T> Ok, NotFound NotFound }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment