import { FreshContext, Handlers } from '$fresh/server.ts' import { db, TablesForModels } from '@lyrics/db.ts' import { ulid } from 'https://deno.land/std@0.209.0/ulid/mod.ts' export function crudHandlerFor< T extends { id: string }, M extends { parse: (a: unknown) => T }, P extends keyof typeof TablesForModels, >(m: M, p: P): Handlers { return { async GET(req: Request, _ctx: FreshContext) { const url = new URL(req.url) const id = url.searchParams.get('id') if (id == null) { return new Response(JSON.stringify(await db[p].all())) } else { return new Response(JSON.stringify(await db[p].get(id))) } }, async PUT(req: Request, _ctx: FreshContext) { const data = m.parse(await req.json()) if (!data.id) data.id = ulid() return new Response(JSON.stringify(await db[p].save(data))) }, async DELETE(req: Request, _ctx: FreshContext) { const url = new URL(req.url) const id = url.searchParams.get('id') if (id == null) { return new Response( JSON.stringify({ message: 'no id query parameter provided' }), { status: 401 }, ) } else { return new Response(JSON.stringify(await db[p].delete(id))) } }, } }