-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
84 lines (65 loc) · 2.16 KB
/
Program.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
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<FruitDb>(opt => opt.UseInMemoryDatabase("FruitList"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Fruit API",
Description = "API for managing a list of fruit and their stock status.",
});
});
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var dbContext = services.GetRequiredService<FruitDb>();
dbContext.Database.EnsureCreated();
}
app.MapGet("/fruitlist", async (FruitDb db) =>
await db.Fruits.ToListAsync())
.WithTags("Get all fruit");
app.MapGet("/fruitlist/instock", async (FruitDb db) =>
await db.Fruits.Where(t => t.Instock).ToListAsync())
.WithTags("Get all fruit that is in stock");
app.MapGet("/fruitlist/{id}", async (int id, FruitDb db) =>
await db.Fruits.FindAsync(id)
is Fruit fruit
? Results.Ok(fruit)
: Results.NotFound())
.WithTags("Get fruit by Id");
app.MapPost("/fruitlist", async (Fruit fruit, FruitDb db) =>
{
db.Fruits.Add(fruit);
await db.SaveChangesAsync();
return Results.Created($"/fruitlist/{fruit.Id}", fruit);
})
.WithTags("Add fruit to list");
app.MapPut("/fruitlist/{id}", async (int id, Fruit inputFruit, FruitDb db) =>
{
var fruit = await db.Fruits.FindAsync(id);
if (fruit is null) return Results.NotFound();
fruit.Name = inputFruit.Name;
fruit.Instock = inputFruit.Instock;
await db.SaveChangesAsync();
return Results.NoContent();
})
.WithTags("Update fruit by Id");
app.MapDelete("/fruitlist/{id}", async (int id, FruitDb db) =>
{
if (await db.Fruits.FindAsync(id) is Fruit fruit)
{
db.Fruits.Remove(fruit);
await db.SaveChangesAsync();
return Results.Ok(fruit);
}
return Results.NotFound();
})
.WithTags("Delete fruit by Id");
app.UseSwagger();
app.UseSwaggerUI();
app.Run();