website/routes/api/webpush/subscription.ts

28 lines
765 B
TypeScript

import { Handlers } from '$fresh/server.ts'
import { respondApi } from ':src/utils.ts'
export const handler: Handlers = {
async POST(request: Request) {
const subscription = await request.json() as PushSubscriptionJSON
saveSubscription(subscription)
return respondApi('success', 'ok')
},
}
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
}
// Store subscription
subscriptions.push(subscription)
localStorage.setItem(itemKey, JSON.stringify(subscriptions))
}