Zod Validator
Validate body with zod.
Install
install external libs @nhttp/zod
.
- Deno
- deno.land
- npm
- Bun
- Yarn
- pnpm
deno add @nhttp/zod
import {...} from "https://deno.land/x/nhttp/lib/zod-validator.ts";
npx jsr add @nhttp/zod
bunx jsr add @nhttp/zod
yarn dlx jsr add @nhttp/zod
pnpm dlx jsr add @nhttp/zod
Usage
import nhttp from "@nhttp/nhttp";
import validate, { z } from "@nhttp/zod";
const User = z.object({
username: z.string(),
password: z.string(),
user_info: z.object({
name: z.string(),
address: z.string(),
}),
});
const app = nhttp();
// validate support all content-type (json, multipart, raw, urlencoded)
app.post("/", validate(User), (rev) => {
return rev.body.user_info;
});
const userId = z.object({
userId: z.number(),
});
// validate path params
app.get("/users/:userId", validate(userId, "params"), (rev) => {
return rev.params;
});
const category = z.object({
category: z.string(),
});
// validate query params
app.get("/posts/:postId", validate(category, "query"), (rev) => {
return rev.query;
});
app.listen(8000, (_err, info) => {
console.log(`Running on port ${info.port}`);
});
With Routing Controller
import { Validate, z } from "@nhttp/zod";
const User = z.object({
username: z.string(),
password: z.string(),
user_info: z.object({
name: z.string(),
address: z.string(),
}),
});
@Controller("/hello")
class HelloController {
@Validate(User)
@Post("/")
save(rev: RequestEvent) {
return "Created";
}
}