|
| 1 | +// Copyright (c) Duende Software. All rights reserved. |
| 2 | +// Licensed under the MIT License. See LICENSE in the project root for license information. |
| 3 | + |
| 4 | +using System.Security.Claims; |
| 5 | +using Microsoft.AspNetCore.Http.Extensions; |
| 6 | + |
| 7 | +namespace Vue.Api; |
| 8 | + |
| 9 | +public static class ToDoEndpointGroup |
| 10 | +{ |
| 11 | + private static readonly List<ToDo> data = new List<ToDo>() |
| 12 | + { |
| 13 | + new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow, Name = "Demo ToDo API", User = "2 (Bob Smith)" }, |
| 14 | + new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow.AddHours(1), Name = "Stop Demo", User = "2 (Bob Smith)" }, |
| 15 | + new ToDo { Id = ToDo.NewId(), Date = DateTimeOffset.UtcNow.AddHours(4), Name = "Have Dinner", User = "1 (Alice Smith)" }, |
| 16 | + }; |
| 17 | + |
| 18 | + public static RouteGroupBuilder ToDoGroup(this RouteGroupBuilder group) |
| 19 | + { |
| 20 | + // GET |
| 21 | + group.MapGet("/", () => data); |
| 22 | + group.MapGet("/{id}", (int id) => |
| 23 | + { |
| 24 | + var item = data.FirstOrDefault(x => x.Id == id); |
| 25 | + }).WithName("todo#show"); |
| 26 | + |
| 27 | + // POST |
| 28 | + group.MapPost("/", (ToDo model, ClaimsPrincipal user, LinkGenerator links) => |
| 29 | + { |
| 30 | + model.Id = ToDo.NewId(); |
| 31 | + model.User = $"{user.FindFirst("sub")?.Value} ({user.FindFirst("name")?.Value})"; |
| 32 | + |
| 33 | + data.Add(model); |
| 34 | + |
| 35 | + var url = links.GetPathByName("todo#show", new { id = model.Id }); |
| 36 | + return Results.Created(url, model); |
| 37 | + }); |
| 38 | + |
| 39 | + // PUT |
| 40 | + group.MapPut("/{id}", (int id, ToDo model, ClaimsPrincipal User) => |
| 41 | + { |
| 42 | + var item = data.FirstOrDefault(x => x.Id == id); |
| 43 | + if (item == null) return Results.NotFound(); |
| 44 | + |
| 45 | + item.Date = model.Date; |
| 46 | + item.Name = model.Name; |
| 47 | + |
| 48 | + return Results.NoContent(); |
| 49 | + }); |
| 50 | + |
| 51 | + // DELETE |
| 52 | + group.MapDelete("/{id}", (int id) => |
| 53 | + { |
| 54 | + var item = data.FirstOrDefault(x => x.Id == id); |
| 55 | + if (item == null) return Results.NotFound(); |
| 56 | + |
| 57 | + data.Remove(item); |
| 58 | + |
| 59 | + return Results.NoContent(); |
| 60 | + }); |
| 61 | + |
| 62 | + return group; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +public class ToDo |
| 67 | +{ |
| 68 | + static int _nextId = 1; |
| 69 | + public static int NewId() |
| 70 | + { |
| 71 | + return _nextId++; |
| 72 | + } |
| 73 | + |
| 74 | + public int Id { get; set; } |
| 75 | + public DateTimeOffset Date { get; set; } |
| 76 | + public string? Name { get; set; } |
| 77 | + public string? User { get; set; } |
| 78 | +} |
0 commit comments