homeman-deno/crud.ts
2024-01-07 10:55:18 -06:00

48 lines
1.5 KiB
TypeScript

import { Handlers } from '$fresh/server.ts'
import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.ts'
import { type AnyZodObject } from 'https://deno.land/x/zod@v3.21.4/mod.ts'
import { db } from '@homeman/models.ts'
export function crudHandler<
SchemaName extends keyof typeof db,
Schema = db[SchemaName
CreateSchema extends AnyZodObject,
Creator extends (s: CreateSchema) => Promise<Schema>,
>(
schema: SchemaName,
createModel: CreateSchema,
creator: Creator,
): Handlers<typeof db[SchemaName]Schema | null> {
return {
async POST(req, _ctx) {
const data = createModel.parse(await req.json())
const newModel: typeof db[SchemaName] = await creator(
data as CreateSchema,
)
const result = await db[schema].create({ data: newModel })
return new Response(JSON.stringify(result))
},
async PUT(req, _ctx) {
const user = UserModel.parse(await req.json())
const result = await db.users.update({ data: user })
return new Response(JSON.stringify(result))
},
async DELETE(req, _ctx) {
const userData = UserModel.pick({ id: true }).parse(await req.json())
const result = await db.users.delete({ where: userData })
return new Response(JSON.stringify(result))
},
async GET(req, _ctx) {
const data = await req.json().catch(() => {})
const userData = UserModel.pick({ id: true }).safeParse(data)
if (userData.success) {
return new Response(
JSON.stringify(await db.users.findFirst({ where: userData.data })),
)
} else {
return new Response(JSON.stringify(await db.users.findMany({})))
}
},
}
}