2024-06-13 12:42:41 +02:00
|
|
|
import { Handlers } from '$fresh/server.ts'
|
2024-07-01 13:11:20 +02:00
|
|
|
import { respondApi } from ':src/utils.ts'
|
2024-06-13 12:42:41 +02:00
|
|
|
|
|
|
|
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))
|
|
|
|
}
|