46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
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 type Method = 'GET' | 'PUT' | 'DELETE'
|
|
|
|
export function isMethod(value: string): value is Method {
|
|
return (value in TablesForModels)
|
|
}
|
|
|
|
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)))
|
|
}
|
|
},
|
|
}
|
|
}
|