-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
76 lines (56 loc) · 2.1 KB
/
Copy pathProgram.cs
File metadata and controls
76 lines (56 loc) · 2.1 KB
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
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<PlayerDB>(opt => opt.UseInMemoryDatabase("PlayerDB"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApiDocument(config => {
config.DocumentName="PlayerAPI";
config.Title = "PlayerAPI v1";
config.Version = "v1";
});
builder.Services.AddCors(options => {
options.AddPolicy("AllowAll", builder => {
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
app.UseCors("AllowAll");
if (app.Environment.IsDevelopment()) {
app.UseOpenApi();
app.UseSwaggerUi(config => {
config.DocumentTitle = "Player API";
config.Path = "/swagger";
config.DocumentPath = "/swagger/{documentName}/swagger.json";
config.DocExpansion = "list";
});
}
app.MapGet("/players", async (PlayerDB db) => await db.Players.ToListAsync());
app.MapGet("/players/{id}", async (int id, PlayerDB db) =>
await db.Players.FindAsync(id)
is Player player
? Results.Ok(player)
: Results.NotFound());
app.MapPost("/players", async (Player player, PlayerDB db) => {
db.Players.Add(player);
await db.SaveChangesAsync();
return Results.Created($"{player.Id}", player);
});
//function to update hiscore for given player
app.MapPut("/players/{id}", async (int id, int hiScore, PlayerDB db) => {
var player = await db.Players.FindAsync(id);
if (player is null) return Results.NotFound();
player.HiScore = hiScore;
await db.SaveChangesAsync();
return Results.Ok($"HiScore updated to {hiScore} for player id {player.Id}");
});
app.MapDelete("/players/{id}", async (int id, PlayerDB db) => {
if (await db.Players.FindAsync(id) is Player player) {
db.Players.Remove(player);
await db.SaveChangesAsync();
return Results.NoContent();
}
return Results.NotFound();
});
app.Run();