Skip to content
54 linesCodeBlameRaw
1import { env } from "cloudflare:workers";
2import { data } from "react-router";
3
4import { notifyClient, type NotifyPreferencesChange, type PushSubscriptionJson } from "@g1t/contracts";
5
6import type { Route } from "./+types/api";
7import { assertSameOrigin, requireUser } from "../../lib/session.server";
8
9function client() {
10 if (!env.NOTIFY) throw data({ error: "Notifications are not set up here." }, { status: 503 });
11 return notifyClient(env.NOTIFY);
12}
13
14/**
15 * The signed-in person's notification settings, as JSON: `GET` their
16 * status (with `?endpoint=` for whether this browser gets pushes), `POST`
17 * a change: `subscribe`, `unsubscribe`, `preferences` or `test`.
18 */
19export async function loader({ context, request }: Route.LoaderArgs) {
20 const user = requireUser(context, request);
21 const endpoint = new URL(request.url).searchParams.get("endpoint");
22 const status = await client().status(user, endpoint);
23 return Response.json(status, { headers: { "cache-control": "no-store" } });
24}
25
26type Sent = {
27 intent?: string;
28 subscription?: PushSubscriptionJson & { expirationTime?: number | null };
29 endpoint?: string;
30 preferences?: NotifyPreferencesChange;
31};
32
33export async function action({ context, request }: Route.ActionArgs) {
34 assertSameOrigin(request);
35 const user = requireUser(context, request);
36 const sent = (await request.json().catch(() => ({}))) as Sent;
37 const notify = client();
38 switch (sent.intent) {
39 case "subscribe": {
40 const s = sent.subscription;
41 if (!s?.endpoint || !s.keys?.p256dh || !s.keys?.auth) return Response.json({ ok: false }, { status: 400 });
42 const subscription: PushSubscriptionJson = { endpoint: s.endpoint, keys: { p256dh: s.keys.p256dh, auth: s.keys.auth } };
43 return Response.json(await notify.subscribe(user, subscription, request.headers.get("user-agent")));
44 }
45 case "unsubscribe":
46 return Response.json(await notify.unsubscribe(user, String(sent.endpoint ?? "")));
47 case "preferences":
48 return Response.json(await notify.setPreferences(user, sent.preferences ?? {}));
49 case "test":
50 return Response.json(await notify.test(user));
51 default:
52 return Response.json({ ok: false }, { status: 400 });
53 }
54}