|
| 1 | +using Microsoft.EntityFrameworkCore; |
| 2 | +using Todo.frockett.Data; |
| 3 | +using Todo.frockett.Models; |
| 4 | + |
| 5 | +namespace Todo.frockett.API; |
| 6 | + |
| 7 | +public class TodoEndpoints |
| 8 | +{ |
| 9 | + // Referenced https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/route-handlers?view=aspnetcore-8.0#endpoint-defined-outside-of-programcs |
| 10 | + |
| 11 | + public static void Map(WebApplication app) |
| 12 | + { |
| 13 | + // Minimal API Endpoints |
| 14 | + app.MapGet("/todoitems", async (TodoContext context) => |
| 15 | + await context.TodoItems.ToListAsync()); |
| 16 | + |
| 17 | + app.MapGet("/todoitems/complete", async (TodoContext context) => |
| 18 | + await context.TodoItems.Where(t => t.IsComplete == true).ToListAsync()); |
| 19 | + |
| 20 | + app.MapGet("/todoitems/{id}", async (int id, TodoContext context) => |
| 21 | + |
| 22 | + await context.TodoItems.FindAsync(id) |
| 23 | + is TodoItem item |
| 24 | + ? Results.Ok(item) |
| 25 | + : Results.NotFound()); |
| 26 | + |
| 27 | + app.MapPost("/todoitems", async (TodoItem item, TodoContext context) => |
| 28 | + { |
| 29 | + context.TodoItems.Add(item); |
| 30 | + await context.SaveChangesAsync(); |
| 31 | + |
| 32 | + return Results.Created($"/todoitems/{item.Id}", item); |
| 33 | + }); |
| 34 | + |
| 35 | + app.MapPut("/todoitems/{id}", async (int id, TodoItem inputTodo, TodoContext context) => |
| 36 | + { |
| 37 | + var item = await context.TodoItems.FindAsync(id); |
| 38 | + |
| 39 | + if (item is null) return Results.NotFound(); |
| 40 | + |
| 41 | + item.Name = inputTodo.Name; |
| 42 | + item.IsComplete = inputTodo.IsComplete; |
| 43 | + |
| 44 | + await context.SaveChangesAsync(); |
| 45 | + |
| 46 | + return Results.NoContent(); |
| 47 | + }); |
| 48 | + |
| 49 | + app.MapDelete("/todoitems/{id}", async (int id, TodoContext context) => |
| 50 | + { |
| 51 | + if (await context.TodoItems.FindAsync(id) is TodoItem todo) |
| 52 | + { |
| 53 | + context.TodoItems.Remove(todo); |
| 54 | + await context.SaveChangesAsync(); |
| 55 | + return Results.NoContent(); |
| 56 | + } |
| 57 | + |
| 58 | + return Results.NotFound(); |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments