All files / Bandstand/src/app/api/push/subscribe route.ts

0% Statements 0/42
0% Branches 0/1
0% Functions 0/1
0% Lines 0/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                                                                                                   
export const dynamic = 'force-dynamic'
 
import {z} from 'zod'
import {prisma} from '@/lib/db'
import {requireUser} from '@/lib/guard'
import {route} from '@/lib/route'
 
const Sub = z.object({
  endpoint: z.string().url().max(2000),
  keys: z.object({p256dh: z.string().max(200), auth: z.string().max(100)}),
  device: z.string().max(60).nullable().optional(),
})
 
/** This device: turn notifications on (its push subscription). */
export const POST = route(async (req: Request) => {
  const {user} = await requireUser()
  const parsed = Sub.safeParse(await req.json())
  if (!parsed.success) return new Response('Bad Request', {status: 400})
  const {endpoint, keys, device} = parsed.data
  // A shared device that someone else had on: it's this person's now
  await prisma.pushSubscription.upsert({
    where: {endpoint},
    create: {
      userId: user.id,
      endpoint,
      p256dh: keys.p256dh,
      auth: keys.auth,
      device: device ?? null,
    },
    update: {
      userId: user.id,
      p256dh: keys.p256dh,
      auth: keys.auth,
      device: device ?? null,
    },
  })
  return new Response(null, {status: 204})
})
 
/** This device: turn notifications off. */
export const DELETE = route(async (req: Request) => {
  const {user} = await requireUser()
  const body = z.object({endpoint: z.string()}).safeParse(await req.json())
  if (!body.success) return new Response('Bad Request', {status: 400})
  await prisma.pushSubscription.deleteMany({
    where: {endpoint: body.data.endpoint, userId: user.id},
  })
  return new Response(null, {status: 204})
})