33 lines
825 B
TypeScript
33 lines
825 B
TypeScript
import { define } from '../../../utils.ts'
|
|
import { respondApi } from ':src/utils.ts'
|
|
import { subscriptions } from ':src/webpush/mod.ts'
|
|
|
|
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))
|
|
}
|
|
},
|
|
})
|
|
|
|
async function saveSubscription(subscription: PushSubscriptionJSON) {
|
|
if (subscription.keys === undefined) {
|
|
throw new Error('no valid key in webpush subscription')
|
|
}
|
|
|
|
const { ok } = await subscriptions.set(
|
|
['subscription', subscription.keys!.auth],
|
|
subscription,
|
|
)
|
|
|
|
if (!ok) {
|
|
throw new Error('subscription saving failed')
|
|
}
|
|
}
|