fix(api/webpush): update subscription handler
This commit is contained in:
parent
0214f587a5
commit
235cab22b7
|
|
@ -59,7 +59,8 @@
|
||||||
"dom",
|
"dom",
|
||||||
"dom.asynciterable",
|
"dom.asynciterable",
|
||||||
"dom.iterable",
|
"dom.iterable",
|
||||||
"deno.ns"
|
"deno.ns",
|
||||||
|
"deno.unstable"
|
||||||
],
|
],
|
||||||
"jsx": "precompile",
|
"jsx": "precompile",
|
||||||
"jsxImportSource": "preact",
|
"jsxImportSource": "preact",
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,32 @@
|
||||||
import { Handlers } from '$fresh/server.ts'
|
import { define } from '../../../utils.ts'
|
||||||
import { respondApi } from ':src/utils.ts'
|
import { respondApi } from ':src/utils.ts'
|
||||||
|
import { subscriptions } from ':src/webpush/mod.ts'
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler = define.handlers({
|
||||||
async POST(request: Request) {
|
async POST(ctx) {
|
||||||
const subscription = await request.json() as PushSubscriptionJSON
|
const subscription = await ctx.req.json() as PushSubscriptionJSON
|
||||||
saveSubscription(subscription)
|
|
||||||
|
try {
|
||||||
|
await saveSubscription(subscription)
|
||||||
return respondApi('success', 'ok')
|
return respondApi('success', 'ok')
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[webpush/subscription]:', error)
|
||||||
|
return respondApi('error', String(error))
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
async function saveSubscription(subscription: PushSubscriptionJSON) {
|
||||||
|
if (subscription.keys === undefined) {
|
||||||
|
throw new Error('no valid key in webpush subscription')
|
||||||
}
|
}
|
||||||
|
|
||||||
function saveSubscription(subscription: PushSubscriptionJSON) {
|
const { ok } = await subscriptions.set(
|
||||||
const itemKey = 'webpush-subscription'
|
['subscription', subscription.keys!.auth],
|
||||||
const subscriptions = JSON.parse(
|
subscription,
|
||||||
localStorage.getItem(itemKey) ?? '[]',
|
)
|
||||||
) as PushSubscriptionJSON[]
|
|
||||||
|
|
||||||
// Prevent duplicate
|
if (!ok) {
|
||||||
const auth = subscription.keys?.auth
|
throw new Error('subscription saving failed')
|
||||||
if (subscriptions.some((sub) => sub.keys?.auth === auth)) {
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store subscription
|
|
||||||
subscriptions.push(subscription)
|
|
||||||
localStorage.setItem(itemKey, JSON.stringify(subscriptions))
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue