-
Notifications
You must be signed in to change notification settings - Fork 141
/
TodoEndpointsV1.cs
106 lines (83 loc) · 2.9 KB
/
TodoEndpointsV1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using WebMinRouteGroup.Data;
namespace WebMinRouteGroup;
public static class TodoEndpointsV1
{
public static RouteGroupBuilder MapTodosApiV1(this RouteGroupBuilder group)
{
group.MapGet("/", GetAllTodos);
group.MapGet("/{id}", GetTodo);
group.MapPost("/", CreateTodo)
.AddEndpointFilter(async (efiContext, next) =>
{
var param = efiContext.GetArgument<TodoDto>(0);
var validationErrors = Utilities.IsValid(param);
if (validationErrors.Any())
{
return Results.ValidationProblem(validationErrors);
}
return await next(efiContext);
});
group.MapPut("/{id}", UpdateTodo);
group.MapDelete("/{id}", DeleteTodo);
return group;
}
// get all todos
// <snippet_1>
public static async Task<Ok<Todo[]>> GetAllTodos(TodoGroupDbContext database)
{
var todos = await database.Todos.ToArrayAsync();
return TypedResults.Ok(todos);
}
// </snippet_1>
// get todo by id
public static async Task<Results<Ok<Todo>, NotFound>> GetTodo(int id, TodoGroupDbContext database)
{
var todo = await database.Todos.FindAsync(id);
if (todo != null)
{
return TypedResults.Ok(todo);
}
return TypedResults.NotFound();
}
// create todo
public static async Task<Created<Todo>> CreateTodo(TodoDto todo, TodoGroupDbContext database)
{
var newTodo = new Todo
{
Title = todo.Title,
Description = todo.Description,
IsDone = todo.IsDone
};
await database.Todos.AddAsync(newTodo);
await database.SaveChangesAsync();
return TypedResults.Created($"/todos/v1/{newTodo.Id}", newTodo);
}
// update todo
public static async Task<Results<Created<Todo>, NotFound>> UpdateTodo(Todo todo, TodoGroupDbContext database)
{
var existingTodo = await database.Todos.FindAsync(todo.Id);
if (existingTodo != null)
{
existingTodo.Title = todo.Title;
existingTodo.Description = todo.Description;
existingTodo.IsDone = todo.IsDone;
await database.SaveChangesAsync();
return TypedResults.Created($"/todos/v1/{existingTodo.Id}", existingTodo);
}
return TypedResults.NotFound();
}
// delete todo
public static async Task<Results<NoContent, NotFound>> DeleteTodo(int id, TodoGroupDbContext database)
{
var todo = await database.Todos.FindAsync(id);
if (todo != null)
{
database.Todos.Remove(todo);
await database.SaveChangesAsync();
return TypedResults.NoContent();
}
return TypedResults.NotFound();
}
}