Skip to content

Instantly share code, notes, and snippets.

@bhumit070
Created May 12, 2023 15:58
Show Gist options
  • Save bhumit070/e39e9d77656fc0505fdce528e2bdb2aa to your computer and use it in GitHub Desktop.
Save bhumit070/e39e9d77656fc0505fdce528e2bdb2aa to your computer and use it in GitHub Desktop.
Way to parse body, params, and query in Nodejs using Zod
import express, { Request, Response } from 'express';
import z, { AnyZodObject, ZodError } from 'zod';
import { generateError } from 'zod-error';
const app = express();
const mySchema = z.object({
body: z.object({
name: z.string(),
}),
params: z.object({
id: z.string(),
}),
});
export async function zParse<T extends AnyZodObject>(
schema: T,
req: Request,
res: Response,
): Promise<z.infer<T>> {
try {
return schema.parseAsync(req);
} catch (error) {
throw error;
}
}
app.all('/', async (req, res) => {
try {
const payload = await zParse(mySchema, req, res);
res.json(payload);
} catch (error) {
if (error instanceof ZodError) {
const errors = generateError(error);
return res.status(400).json({ error: errors });
}
return res.status(500).json({ error: 'Internal Server Error' });
}
});
const PORT = process.env.PORT || 5001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment