import type { Db } from '../db/mod.ts' import type { Resource } from '../models/mod.ts' import type { UUID } from '../../types.ts' import type { ResourceBuilder, ResourceType } from './types.ts' import { respondJson } from './utils.ts' export async function resourceHandler( type: ResourceType, Builder: ResourceBuilder, db: Db, req: Request, id?: string, ): Promise { if (req.method === 'POST') { try { const json = await req.json() as T try { //@ts-expect-error Extends from Resource const resource = Builder.create(json) //@ts-expect-error not a generic const result = await db.resource[type].set(resource) if (result.ok) { //@ts-expect-error generic to fix return respondJson(resource) } else { return respondJson(new Error(`can't insert ${resource} in db`)) } } catch (error) { return respondJson(error) } } catch (error) { return respondJson(error) } } if (req.method === 'GET') { if (id === undefined) { return respondJson(new Error('missing "id" for "GET"')) } try { const resource = await db.resource[type].get({ uuid: id as UUID }) //@ts-expect-error generic to fix return respondJson(resource) } catch { return respondJson( new Error(`can't find any ${type} with the current uuid ${id}`), ) } } if (req.method === 'PATCH') { throw new Error('not implemented') } if (req.method === 'DELETE') { throw new Error('not implemented') } return respondJson(new Error(`method "${req.method}" is not allowed`)) }