Zod
Zod is to infer the type during runtime. Typescript can help during the compile time however not runtime.
We can create a zod object like so
const DepositRequestSchema = z.object({
playerId: z.string().min(1),
amount: z.number().int().positive()
})
From here, we can validate this object by doing
DepositRequestSchema.safeParse(some_object) -> { success: bool, data: T, error?: ZodError }
Sample:
import Fastify from "fastify";
import { z } from "zod";
const app = Fastify({ logger: true })
const DepositRequestSchema = z.object({
playerId: z.string().min(1),
amount: z.number().int().positive()
})
type DepositRequest = z.infer<typeof DepositRequestSchema>;
app.get("/health", async () => ({ status: "ok" }))
app.post("/deposit", async (request, response) => {
const parsed = DepositRequestSchema.safeParse(request.body);
if (!parsed.success) {
return response.code(400).send({ error: parsed.error.flatten() });
}
const { playerId, amount } : DepositRequest = parsed.data;
return response.code(201).send({ ok: true, playerId, amount })
})
await app.listen({ port: 8080 })