File size: 1,420 Bytes
2c16c8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { Request, Response, NextFunction } from 'express';
import { ZodSchema, ZodError } from 'zod';

interface ValidateOptions {
  body?: ZodSchema<any>;
  query?: ZodSchema<any>;
  params?: ZodSchema<any>;
}

export function Validate(schemas: ValidateOptions): MethodDecorator {
  return function (

    target: any,

    propertyKey: string | symbol,

    descriptor: PropertyDescriptor

  ) {
    const originalMethod = descriptor.value;

    descriptor.value = async function (

      req: Request,

      res: Response,

      next: NextFunction

    ) {
      try {
        if (schemas.body) {
          req.body = schemas.body.parse(req.body);
        }
        if (schemas.query) {
          req.query = schemas.query.parse(req.query);
        }
        if (schemas.params) {
          req.params = schemas.params.parse(req.params);
        }

        return await originalMethod.call(this, req, res, next);
      } catch (err: any) {
        if (err instanceof ZodError) {
          const formattedErrors = err.issues.map(issue => ({
            field: issue.path.join('.'),
            error: issue.message
          }));

          return res.error(400, 'VALIDATION_ERROR', 'Failed to validate data', formattedErrors);
        }

        return res.error(500, 'INTERNAL_SERVER_ERROR', 'An unexpected error occurred');
      }
    };

    return descriptor;
  };
}