Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { env } from 'cloudflare:workers'
3
4import { getDb } from '#/db/index.ts'
5import { jsonError } from '#/server/admin.ts'
6import { getAuth } from '#/server/auth.ts'
7import { requireAgent } from '#/server/require-agent.ts'
8import {
9 createSubscription,
10 listSubscriptions,
11 parseCreateSubscriptionBody,
12} from '#/server/subscriptions-api.ts'
13
14export const Route = createFileRoute('/v1/subscriptions/')({
15 server: {
16 handlers: {
17 GET: async ({ request }) => {
18 const auth = await requireAgent(getAuth(), request, {
19 capability: 'manage_subscriptions',
20 })
21 if (!auth.ok) return auth.response
22 return Response.json(
23 await listSubscriptions(getDb(env), auth.principal),
24 )
25 },
26 POST: async ({ request }) => {
27 const auth = await requireAgent(getAuth(), request, {
28 capability: 'manage_subscriptions',
29 })
30 if (!auth.ok) return auth.response
31 let raw: unknown
32 try {
33 raw = await request.json()
34 } catch {
35 return jsonError(400, 'invalid_json', 'Request body must be JSON.')
36 }
37 const body = parseCreateSubscriptionBody(raw)
38 if (!body) {
39 return jsonError(
40 400,
41 'invalid_request',
42 'Body must be { url: public https URL, events: ChangeType[], provider?: string }.',
43 )
44 }
45 const outcome = await createSubscription(
46 getDb(env),
47 auth.principal,
48 body,
49 )
50 if (!outcome.ok) {
51 return jsonError(outcome.status, outcome.code, outcome.message)
52 }
53 return Response.json(outcome.result, { status: 201 })
54 },
55 },
56 },
57})