Zod Validation Decorator (Express.js)

JS
S
JavaScript

A TypeScript decorator that automatically validates incoming HTTP request bodies against a Zod schema, providing clean error handling and type safety without cluttering controller logic.

1import { Request, Response } from 'express';
2import { z } from 'zod';
3
4// Decorator factory
5function ValidateBody(schema: z.ZodSchema) {
6  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
7    const originalMethod = descriptor.value;
8
9    descriptor.value = async function(req: Request, res: Response) {
10      try {
11        req.body = schema.parse(req.body);
12        return await originalMethod.apply(this, [req, res]);
13      } catch (error) {
14        if (error instanceof z.ZodError) {
15          return res.status(400).json({ errors: error.errors });
16        }
17        throw error;
18      }
19    };
20  };
21}
22
23// Usage
24class UserController {
25  @ValidateBody(UserSchema)
26  async createUser(req: Request, res: Response) {
27    const user = await UserModel.create(req.body);
28    return res.status(201).json(user);
29  }
30}

Created on 11/12/2024