1
+ using System . Security . Claims ;
2
+ using Microsoft . AspNetCore . Authorization ;
3
+ using Microsoft . EntityFrameworkCore ;
4
+
5
+ namespace BlazingPizza . Server ;
6
+
7
+ public static class PizzaApiExtensions
8
+ {
9
+
10
+ public static WebApplication MapPizzaApi ( this WebApplication app )
11
+ {
12
+
13
+ // Subscribe to notifications
14
+ app . MapPut ( "/notifications/subscribe" , [ Authorize ] async (
15
+ HttpContext context ,
16
+ PizzaStoreContext db ,
17
+ NotificationSubscription subscription ) =>
18
+ {
19
+
20
+ // We're storing at most one subscription per user, so delete old ones.
21
+ // Alternatively, you could let the user register multiple subscriptions from different browsers/devices.
22
+ var userId = GetUserId ( context ) ;
23
+ var oldSubscriptions = db . NotificationSubscriptions . Where ( e => e . UserId == userId ) ;
24
+ db . NotificationSubscriptions . RemoveRange ( oldSubscriptions ) ;
25
+
26
+ // Store new subscription
27
+ subscription . UserId = userId ;
28
+ db . NotificationSubscriptions . Attach ( subscription ) ;
29
+
30
+ await db . SaveChangesAsync ( ) ;
31
+ return Results . Ok ( subscription ) ;
32
+
33
+ } ) ;
34
+
35
+ // Specials
36
+ app . MapGet ( "/specials" , async ( PizzaStoreContext db ) =>
37
+ {
38
+
39
+ var specials = await db . Specials . ToListAsync ( ) ;
40
+ return Results . Ok ( specials ) ;
41
+
42
+ } ) ;
43
+
44
+ // Toppings
45
+ app . MapGet ( "/toppings" , async ( PizzaStoreContext db ) =>
46
+ {
47
+ var toppings = await db . Toppings . OrderBy ( t => t . Name ) . ToListAsync ( ) ;
48
+ return Results . Ok ( toppings ) ;
49
+ } ) ;
50
+
51
+ return app ;
52
+
53
+ }
54
+
55
+ private static string GetUserId ( HttpContext context )
56
+ {
57
+ return context . User . FindFirstValue ( ClaimTypes . NameIdentifier ) ;
58
+ }
59
+
60
+ }
0 commit comments