deno-fresh-saurpc-lyrics/api.ts

41 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-02-20 13:29:29 -06:00
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'
2024-02-18 14:18:51 -06:00
export function crudHandlerFor<
T extends { id: string },
2024-02-20 13:29:29 -06:00
M extends { parse: (a: unknown) => T },
2024-02-18 14:18:51 -06:00
P extends keyof typeof TablesForModels,
2024-02-20 13:29:29 -06:00
>(m: M, p: P): Handlers {
2024-02-18 14:18:51 -06:00
return {
2024-02-20 13:29:29 -06:00
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)))
}
},
2024-02-18 14:18:51 -06:00
}
}