Created
May 24, 2025 00:34
-
-
Save BashkaMen/9f3ad42afd64a1a98f9f6469adfedd76 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { randomUUIDv7 } from "bun"; | |
import z from "zod"; | |
const mk_endpoint = <TReq, TRes, TPath extends string = string>(meta: { | |
path: TPath; | |
method?: string; | |
input_schema: z.ZodType<TReq>; | |
output_schema: z.ZodType<TRes>; | |
handler: (args: { | |
input: TReq; | |
request: Bun.BunRequest<TPath>; | |
}) => Promise<TRes>; | |
}) => { | |
const handler = async (request: Bun.BunRequest<TPath>) => { | |
try { | |
const json = (await request.json()) as object; | |
const headers = Object.fromEntries(request.headers.entries()); | |
const input = { | |
...headers, | |
...request.params, | |
...json, | |
}; | |
const req = meta.input_schema.safeParse(input); | |
if (!req.success) { | |
return Response.json( | |
{ error: "invalid input", details: req.error.flatten() }, | |
{ status: 400 } | |
); | |
} | |
const result = await meta.handler({ | |
input: req.data, | |
request: request, | |
}); | |
const valid_reponse = meta.output_schema.safeParse(result); | |
if (!valid_reponse.success) { | |
throw valid_reponse.error; | |
} | |
return Response.json(result, { status: 200 }); | |
} catch (e) { | |
console.error(e); | |
return Response.json({ error: "internal error" }, { status: 500 }); | |
} | |
}; | |
return { [meta.path]: { [meta.method ?? "POST"]: handler } }; | |
}; | |
const create_user = mk_endpoint({ | |
path: "/user/create/:id", | |
input_schema: z.object({ | |
id: z.string().uuid(), | |
name: z.string(), | |
role: z.string(), | |
}), | |
output_schema: z.object({ id: z.string().uuid(), name: z.string() }), | |
handler: async ({ input: req }) => { | |
return { ...req, name: req.name.toUpperCase() }; | |
}, | |
}); | |
Bun.serve({ | |
port: 3000, | |
routes: { | |
...create_user, | |
}, | |
}); |
currently support binding params from body, route, headers with full static typing
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
todo add middlewares with next func