zhttp
A small library that brings zod
, express
, and static-path
together to create type safe HTTP endpoints for clients and servers.
Getting Started
Install zhttp
and its peer dependencies.
npm i @danprince/zhttp express @types/express zod static-path
Example
Define your endpoints somewhere that both your client and server can import from.
import { endpoint } from "@danprince/zhttp";
import { z } from "zod";
import { path } from "path";
export let sendMessage = endpoint({
path: path("/message/:to"),
method: "post",
request: z.object({
subject: z.string(),
text: z.string(),
}),
response: z.object({
status: z.union([
z.literal("success"),
z.literal("pending"),
z.literal("failure"),
]),
}),
});
Then create corresponding server side route handlers.
import { createRouter } from "@danprince/zhttp/express";
import { sendMessage } from "../shared/endpoints";
let router = createRouter();
router.use(sendMessage, async (req, res) => {
let { subject, text } = req.body;
res.json({ status: "success" });
});
And finally, the client side.
import { fetchJson } from "@danprince/zhttp/fetch";
import { sendMessage } from "../shared/endpoints";
let res = await fetchJson(sendMessage, {
params: { to: "howard" },
body: {
subject: "Hello!",
text: "This is a message",
},
});
res.status