-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dac41d2
commit 7c41768
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
60 changes: 60 additions & 0 deletions
60
save-points/00-get-started/BlazingPizza.Server/PizzaApiExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
using System.Security.Claims; | ||
using Microsoft.AspNetCore.Authorization; | ||
using Microsoft.EntityFrameworkCore; | ||
|
||
namespace BlazingPizza.Server; | ||
|
||
public static class PizzaApiExtensions | ||
{ | ||
|
||
public static WebApplication MapPizzaApi(this WebApplication app) | ||
{ | ||
|
||
// Subscribe to notifications | ||
app.MapPut("/notifications/subscribe", [Authorize] async ( | ||
HttpContext context, | ||
PizzaStoreContext db, | ||
NotificationSubscription subscription) => | ||
{ | ||
|
||
// We're storing at most one subscription per user, so delete old ones. | ||
// Alternatively, you could let the user register multiple subscriptions from different browsers/devices. | ||
var userId = GetUserId(context); | ||
var oldSubscriptions = db.NotificationSubscriptions.Where(e => e.UserId == userId); | ||
db.NotificationSubscriptions.RemoveRange(oldSubscriptions); | ||
|
||
// Store new subscription | ||
subscription.UserId = userId; | ||
db.NotificationSubscriptions.Attach(subscription); | ||
|
||
await db.SaveChangesAsync(); | ||
return Results.Ok(subscription); | ||
|
||
}); | ||
|
||
// Specials | ||
app.MapGet("/specials", async (PizzaStoreContext db) => | ||
{ | ||
|
||
var specials = await db.Specials.ToListAsync(); | ||
return Results.Ok(specials); | ||
|
||
}); | ||
|
||
// Toppings | ||
app.MapGet("/toppings", async (PizzaStoreContext db) => | ||
{ | ||
var toppings = await db.Toppings.OrderBy(t => t.Name).ToListAsync(); | ||
return Results.Ok(toppings); | ||
}); | ||
|
||
return app; | ||
|
||
} | ||
|
||
private static string GetUserId(HttpContext context) | ||
{ | ||
return context.User.FindFirstValue(ClaimTypes.NameIdentifier); | ||
} | ||
|
||
} |