diff --git a/deno.json b/deno.json index 2bdd977..e24ace7 100644 --- a/deno.json +++ b/deno.json @@ -59,7 +59,8 @@ "dom", "dom.asynciterable", "dom.iterable", - "deno.ns" + "deno.ns", + "deno.unstable" ], "jsx": "precompile", "jsxImportSource": "preact", diff --git a/routes/api/webpush/subscription.ts b/routes/api/webpush/subscription.ts index dc5a242..4888f59 100644 --- a/routes/api/webpush/subscription.ts +++ b/routes/api/webpush/subscription.ts @@ -1,27 +1,32 @@ -import { Handlers } from '$fresh/server.ts' +import { define } from '../../../utils.ts' import { respondApi } from ':src/utils.ts' +import { subscriptions } from ':src/webpush/mod.ts' -export const handler: Handlers = { - async POST(request: Request) { - const subscription = await request.json() as PushSubscriptionJSON - saveSubscription(subscription) - return respondApi('success', 'ok') +export const handler = define.handlers({ + async POST(ctx) { + const subscription = await ctx.req.json() as PushSubscriptionJSON + + try { + await saveSubscription(subscription) + return respondApi('success', 'ok') + } catch (error) { + console.error('[webpush/subscription]:', error) + return respondApi('error', String(error)) + } }, -} +}) -function saveSubscription(subscription: PushSubscriptionJSON) { - const itemKey = 'webpush-subscription' - const subscriptions = JSON.parse( - localStorage.getItem(itemKey) ?? '[]', - ) as PushSubscriptionJSON[] - - // Prevent duplicate - const auth = subscription.keys?.auth - if (subscriptions.some((sub) => sub.keys?.auth === auth)) { - return +async function saveSubscription(subscription: PushSubscriptionJSON) { + if (subscription.keys === undefined) { + throw new Error('no valid key in webpush subscription') } - // Store subscription - subscriptions.push(subscription) - localStorage.setItem(itemKey, JSON.stringify(subscriptions)) + const { ok } = await subscriptions.set( + ['subscription', subscription.keys!.auth], + subscription, + ) + + if (!ok) { + throw new Error('subscription saving failed') + } }