express-zod-safe 1.5.2 → 1.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.d.mts +95 -0
- package/dist/{esm/index.d.ts → index.d.ts} +15 -11
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +47 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +24 -11
- package/dist/cjs/index.js +0 -113
- package/dist/esm/index.js +0 -95
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<img alt="Version" src="https://img.shields.io/npm/v/express-zod-safe.svg?label=Version">
|
|
8
8
|
</a>
|
|
9
9
|
<a href="https://github.com/AngaBlue/exe/blob/master/LICENSE" target="_blank">
|
|
10
|
-
<img alt="
|
|
10
|
+
<img alt="Licence: MIT" src="https://img.shields.io/npm/l/express-zod-safe?color=green&label=Licence" />
|
|
11
11
|
</a>
|
|
12
12
|
</p>
|
|
13
13
|
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { Request, Response, NextFunction, RequestHandler } from 'express';
|
|
2
|
+
import { ZodTypeAny, ZodRawShape, z, ZodError } from 'zod';
|
|
3
|
+
|
|
4
|
+
declare const types: readonly ["query", "params", "body"];
|
|
5
|
+
declare const emptyObjectSchema: z.ZodObject<{}, "strict", ZodTypeAny, {}, {}>;
|
|
6
|
+
type EmptyValidationSchema = typeof emptyObjectSchema;
|
|
7
|
+
/**
|
|
8
|
+
* Generates a middleware function for Express.js that validates request params, query, and body.
|
|
9
|
+
* This function uses Zod schemas to perform validation against the provided schema definitions.
|
|
10
|
+
*
|
|
11
|
+
* @param schemas - An object containing Zod schemas for params, query, and body. Optional handler for custom error handling.
|
|
12
|
+
* @returns An Express.js middleware function that validates the request based on the provided schemas.
|
|
13
|
+
* It attaches validated data to the request object and sends error details if validation fails.
|
|
14
|
+
* @template TParams - Type definition for params schema.
|
|
15
|
+
* @template TQuery - Type definition for query schema.
|
|
16
|
+
* @template TBody - Type definition for body schema.
|
|
17
|
+
* @example
|
|
18
|
+
* // Example usage in an Express.js route
|
|
19
|
+
* import express from 'express';
|
|
20
|
+
* import validate from 'express-zod-safe';
|
|
21
|
+
* import { z } from 'zod';
|
|
22
|
+
*
|
|
23
|
+
* const app = express();
|
|
24
|
+
*
|
|
25
|
+
* // Define your Zod schemas
|
|
26
|
+
* const params = {
|
|
27
|
+
* userId: z.string().uuid(),
|
|
28
|
+
* };
|
|
29
|
+
* const query = {
|
|
30
|
+
* age: z.coerce.number().optional(),
|
|
31
|
+
* };
|
|
32
|
+
* const body = {
|
|
33
|
+
* name: z.string(),
|
|
34
|
+
* email: z.string().email(),
|
|
35
|
+
* };
|
|
36
|
+
*
|
|
37
|
+
* // Use the validate middleware in your route
|
|
38
|
+
* app.post('/user/:userId', validate({ params, query, body }), (req, res) => {
|
|
39
|
+
* // Your route logic here
|
|
40
|
+
* res.send('User data is valid!');
|
|
41
|
+
* });
|
|
42
|
+
*
|
|
43
|
+
* app.listen(3000, () => console.log('Server running on port 3000'));
|
|
44
|
+
*/
|
|
45
|
+
declare function validate<TParams extends ValidationSchema = EmptyValidationSchema, TQuery extends ValidationSchema = EmptyValidationSchema, TBody extends ValidationSchema = EmptyValidationSchema>(schemas: CompleteValidationSchema<TParams, TQuery, TBody>): RequestHandler<ZodOutput<TParams>, any, ZodOutput<TBody>, ZodOutput<TQuery>>;
|
|
46
|
+
/**
|
|
47
|
+
* Describes the types of data that can be validated: 'query', 'params', or 'body'.
|
|
48
|
+
*/
|
|
49
|
+
type DataType = (typeof types)[number];
|
|
50
|
+
/**
|
|
51
|
+
* Defines the structure of an error item, containing the type of validation that failed (params, query, or body)
|
|
52
|
+
* and the associated ZodError.
|
|
53
|
+
*/
|
|
54
|
+
interface ErrorListItem {
|
|
55
|
+
type: DataType;
|
|
56
|
+
errors: ZodError;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Represents an Express.js error request handler where the params, query and body are of unknown type as validation failed.
|
|
60
|
+
*/
|
|
61
|
+
type ErrorRequestHandler<P = unknown, ResBody = any, ReqBody = unknown, ReqQuery = unknown, LocalsObj extends Record<string, any> = Record<string, any>> = (err: ErrorListItem[], req: Request<P, ResBody, ReqBody, ReqQuery, LocalsObj>, res: Response<ResBody, LocalsObj>, next: NextFunction) => void | Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Represents a generic type for route validation, which can be applied to params, query, or body.
|
|
64
|
+
* Each key-value pair represents a field and its corresponding Zod validation schema.
|
|
65
|
+
*/
|
|
66
|
+
type ValidationSchema = ZodTypeAny | ZodRawShape;
|
|
67
|
+
/**
|
|
68
|
+
* Defines the structure for the schemas provided to the validate middleware.
|
|
69
|
+
* Each property corresponds to a different part of the request (params, query, body)
|
|
70
|
+
* and should be a record of Zod types for validation. Optional handler for custom error handling.
|
|
71
|
+
*
|
|
72
|
+
* @template TParams - Type definition for params schema.
|
|
73
|
+
* @template TQuery - Type definition for query schema.
|
|
74
|
+
* @template TBody - Type definition for body schema.
|
|
75
|
+
*/
|
|
76
|
+
interface CompleteValidationSchema<TParams extends ValidationSchema = EmptyValidationSchema, TQuery extends ValidationSchema = EmptyValidationSchema, TBody extends ValidationSchema = EmptyValidationSchema> {
|
|
77
|
+
handler?: ErrorRequestHandler;
|
|
78
|
+
params?: TParams;
|
|
79
|
+
query?: TQuery;
|
|
80
|
+
body?: TBody;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Represents the output type of a Zod validation schema.
|
|
84
|
+
* This is used to infer the TypeScript type from a Zod schema,
|
|
85
|
+
* providing typesafe access to the validated data.
|
|
86
|
+
*
|
|
87
|
+
* @template T - The validation type (params, query, or body).
|
|
88
|
+
*/
|
|
89
|
+
type ZodOutput<T extends ValidationSchema> = T extends ZodRawShape ? z.ZodObject<T>['_output'] : T['_output'];
|
|
90
|
+
/**
|
|
91
|
+
* A utility type to ensure other middleware types don't conflict with the validate middleware.
|
|
92
|
+
*/
|
|
93
|
+
type WeakRequestHandler = RequestHandler<unknown, unknown, unknown, Record<string, unknown>>;
|
|
94
|
+
|
|
95
|
+
export { type CompleteValidationSchema, type EmptyValidationSchema, type ErrorListItem, type ErrorRequestHandler, type ValidationSchema, type WeakRequestHandler, type ZodOutput, validate as default };
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
1
|
+
import { Request, Response, NextFunction, RequestHandler } from 'express';
|
|
2
|
+
import { ZodTypeAny, ZodRawShape, z, ZodError } from 'zod';
|
|
3
|
+
|
|
3
4
|
declare const types: readonly ["query", "params", "body"];
|
|
4
5
|
declare const emptyObjectSchema: z.ZodObject<{}, "strict", ZodTypeAny, {}, {}>;
|
|
5
|
-
|
|
6
|
+
type EmptyValidationSchema = typeof emptyObjectSchema;
|
|
6
7
|
/**
|
|
7
8
|
* Generates a middleware function for Express.js that validates request params, query, and body.
|
|
8
9
|
* This function uses Zod schemas to perform validation against the provided schema definitions.
|
|
@@ -41,7 +42,7 @@ export type EmptyValidationSchema = typeof emptyObjectSchema;
|
|
|
41
42
|
*
|
|
42
43
|
* app.listen(3000, () => console.log('Server running on port 3000'));
|
|
43
44
|
*/
|
|
44
|
-
|
|
45
|
+
declare function validate<TParams extends ValidationSchema = EmptyValidationSchema, TQuery extends ValidationSchema = EmptyValidationSchema, TBody extends ValidationSchema = EmptyValidationSchema>(schemas: CompleteValidationSchema<TParams, TQuery, TBody>): RequestHandler<ZodOutput<TParams>, any, ZodOutput<TBody>, ZodOutput<TQuery>>;
|
|
45
46
|
/**
|
|
46
47
|
* Describes the types of data that can be validated: 'query', 'params', or 'body'.
|
|
47
48
|
*/
|
|
@@ -50,19 +51,19 @@ type DataType = (typeof types)[number];
|
|
|
50
51
|
* Defines the structure of an error item, containing the type of validation that failed (params, query, or body)
|
|
51
52
|
* and the associated ZodError.
|
|
52
53
|
*/
|
|
53
|
-
|
|
54
|
+
interface ErrorListItem {
|
|
54
55
|
type: DataType;
|
|
55
56
|
errors: ZodError;
|
|
56
57
|
}
|
|
57
58
|
/**
|
|
58
59
|
* Represents an Express.js error request handler where the params, query and body are of unknown type as validation failed.
|
|
59
60
|
*/
|
|
60
|
-
|
|
61
|
+
type ErrorRequestHandler<P = unknown, ResBody = any, ReqBody = unknown, ReqQuery = unknown, LocalsObj extends Record<string, any> = Record<string, any>> = (err: ErrorListItem[], req: Request<P, ResBody, ReqBody, ReqQuery, LocalsObj>, res: Response<ResBody, LocalsObj>, next: NextFunction) => void | Promise<void>;
|
|
61
62
|
/**
|
|
62
63
|
* Represents a generic type for route validation, which can be applied to params, query, or body.
|
|
63
64
|
* Each key-value pair represents a field and its corresponding Zod validation schema.
|
|
64
65
|
*/
|
|
65
|
-
|
|
66
|
+
type ValidationSchema = ZodTypeAny | ZodRawShape;
|
|
66
67
|
/**
|
|
67
68
|
* Defines the structure for the schemas provided to the validate middleware.
|
|
68
69
|
* Each property corresponds to a different part of the request (params, query, body)
|
|
@@ -72,7 +73,7 @@ export type ValidationSchema = ZodTypeAny | ZodRawShape;
|
|
|
72
73
|
* @template TQuery - Type definition for query schema.
|
|
73
74
|
* @template TBody - Type definition for body schema.
|
|
74
75
|
*/
|
|
75
|
-
|
|
76
|
+
interface CompleteValidationSchema<TParams extends ValidationSchema = EmptyValidationSchema, TQuery extends ValidationSchema = EmptyValidationSchema, TBody extends ValidationSchema = EmptyValidationSchema> {
|
|
76
77
|
handler?: ErrorRequestHandler;
|
|
77
78
|
params?: TParams;
|
|
78
79
|
query?: TQuery;
|
|
@@ -85,9 +86,12 @@ export interface CompleteValidationSchema<TParams extends ValidationSchema = Emp
|
|
|
85
86
|
*
|
|
86
87
|
* @template T - The validation type (params, query, or body).
|
|
87
88
|
*/
|
|
88
|
-
|
|
89
|
+
type ZodOutput<T extends ValidationSchema> = T extends ZodRawShape ? z.ZodObject<T>['_output'] : T['_output'];
|
|
89
90
|
/**
|
|
90
91
|
* A utility type to ensure other middleware types don't conflict with the validate middleware.
|
|
91
92
|
*/
|
|
92
|
-
|
|
93
|
-
|
|
93
|
+
type WeakRequestHandler = RequestHandler<unknown, unknown, unknown, Record<string, unknown>>;
|
|
94
|
+
|
|
95
|
+
// @ts-ignore
|
|
96
|
+
export = validate;
|
|
97
|
+
export type { CompleteValidationSchema, EmptyValidationSchema, ErrorListItem, ErrorRequestHandler, ValidationSchema, WeakRequestHandler, ZodOutput };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/index.ts
|
|
2
|
+
var _express = require('express'); var _express2 = _interopRequireDefault(_express);
|
|
3
|
+
var _zod = require('zod');
|
|
4
|
+
var types = ["query", "params", "body"];
|
|
5
|
+
var emptyObjectSchema = _zod.z.object({}).strict();
|
|
6
|
+
function isZodSchema(schema) {
|
|
7
|
+
return !!schema && typeof schema.safeParseAsync === "function";
|
|
8
|
+
}
|
|
9
|
+
var descriptor = Object.getOwnPropertyDescriptor(_express2.default.request, "query");
|
|
10
|
+
if (descriptor) {
|
|
11
|
+
Object.defineProperty(_express2.default.request, "query", {
|
|
12
|
+
get() {
|
|
13
|
+
if (this._query) return this._query;
|
|
14
|
+
return _optionalChain([descriptor, 'optionalAccess', _ => _.get, 'optionalAccess', _2 => _2.call, 'call', _3 => _3(this)]);
|
|
15
|
+
},
|
|
16
|
+
set(query) {
|
|
17
|
+
this._query = query;
|
|
18
|
+
},
|
|
19
|
+
configurable: true,
|
|
20
|
+
enumerable: true
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function validate(schemas) {
|
|
24
|
+
const validation = {
|
|
25
|
+
params: isZodSchema(schemas.params) ? schemas.params : _zod.z.object(_nullishCoalesce(schemas.params, () => ( {}))).strict(),
|
|
26
|
+
query: isZodSchema(schemas.query) ? schemas.query : _zod.z.object(_nullishCoalesce(schemas.query, () => ( {}))).strict(),
|
|
27
|
+
body: isZodSchema(schemas.body) ? schemas.body : _zod.z.object(_nullishCoalesce(schemas.body, () => ( {}))).strict()
|
|
28
|
+
};
|
|
29
|
+
return async (req, res, next) => {
|
|
30
|
+
const errors = [];
|
|
31
|
+
for (const type of types) {
|
|
32
|
+
const parsed = await validation[type].safeParseAsync(_nullishCoalesce(req[type], () => ( {})));
|
|
33
|
+
if (parsed.success) req[type] = parsed.data;
|
|
34
|
+
else errors.push({ type, errors: parsed.error });
|
|
35
|
+
}
|
|
36
|
+
if (errors.length > 0) {
|
|
37
|
+
if (schemas.handler) return schemas.handler(errors, req, res, next);
|
|
38
|
+
res.status(400).send(errors.map((error) => ({ type: error.type, errors: error.errors })));
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
return next();
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
exports.default = validate;
|
|
47
|
+
|
|
48
|
+
module.exports = exports.default;
|
|
49
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-zod-safe/express-zod-safe/dist/index.js","../src/index.ts"],"names":[],"mappings":"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","file":"/home/runner/work/express-zod-safe/express-zod-safe/dist/index.js","sourcesContent":[null,"/// <reference types=\"./express.d.ts\" />\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport express from 'express';\nimport { type ZodError, type ZodRawShape, type ZodSchema, type ZodTypeAny, z } from 'zod';\n\nconst types = ['query', 'params', 'body'] as const;\nconst emptyObjectSchema = z.object({}).strict();\nexport type EmptyValidationSchema = typeof emptyObjectSchema;\n\n/**\n * A ZodSchema type guard.\n * @param schema The Zod schema to check.\n * @returns Whether the provided schema is a ZodSchema.\n */\nfunction isZodSchema(schema: unknown): schema is ZodSchema {\n\treturn !!schema && typeof (schema as ZodSchema).safeParseAsync === 'function';\n}\n\n// Override express@^5 request.query getter to provider setter\nconst descriptor = Object.getOwnPropertyDescriptor(express.request, 'query');\nif (descriptor) {\n\tObject.defineProperty(express.request, 'query', {\n\t\tget(this: Request) {\n\t\t\tif (this._query) return this._query;\n\t\t\treturn descriptor?.get?.call(this);\n\t\t},\n\t\tset(this: Request, query: unknown) {\n\t\t\tthis._query = query;\n\t\t},\n\t\tconfigurable: true,\n\t\tenumerable: true\n\t});\n}\n\n/**\n * Generates a middleware function for Express.js that validates request params, query, and body.\n * This function uses Zod schemas to perform validation against the provided schema definitions.\n *\n * @param schemas - An object containing Zod schemas for params, query, and body. Optional handler for custom error handling.\n * @returns An Express.js middleware function that validates the request based on the provided schemas.\n * It attaches validated data to the request object and sends error details if validation fails.\n * @template TParams - Type definition for params schema.\n * @template TQuery - Type definition for query schema.\n * @template TBody - Type definition for body schema.\n * @example\n * // Example usage in an Express.js route\n * import express from 'express';\n * import validate from 'express-zod-safe';\n * import { z } from 'zod';\n *\n * const app = express();\n *\n * // Define your Zod schemas\n * const params = {\n * userId: z.string().uuid(),\n * };\n * const query = {\n * age: z.coerce.number().optional(),\n * };\n * const body = {\n * name: z.string(),\n * email: z.string().email(),\n * };\n *\n * // Use the validate middleware in your route\n * app.post('/user/:userId', validate({ params, query, body }), (req, res) => {\n * // Your route logic here\n * res.send('User data is valid!');\n * });\n *\n * app.listen(3000, () => console.log('Server running on port 3000'));\n */\nexport default function validate<\n\tTParams extends ValidationSchema = EmptyValidationSchema,\n\tTQuery extends ValidationSchema = EmptyValidationSchema,\n\tTBody extends ValidationSchema = EmptyValidationSchema\n>(schemas: CompleteValidationSchema<TParams, TQuery, TBody>): RequestHandler<ZodOutput<TParams>, any, ZodOutput<TBody>, ZodOutput<TQuery>> {\n\t// Create validation objects for each type\n\tconst validation = {\n\t\tparams: isZodSchema(schemas.params) ? schemas.params : z.object(schemas.params ?? {}).strict(),\n\t\tquery: isZodSchema(schemas.query) ? schemas.query : z.object(schemas.query ?? {}).strict(),\n\t\tbody: isZodSchema(schemas.body) ? schemas.body : z.object(schemas.body ?? {}).strict()\n\t};\n\n\treturn async (req, res, next): Promise<void> => {\n\t\tconst errors: ErrorListItem[] = [];\n\n\t\t// Validate all types (params, query, body)\n\t\tfor (const type of types) {\n\t\t\tconst parsed = await validation[type].safeParseAsync(req[type] ?? {});\n\t\t\tif (parsed.success) req[type] = parsed.data;\n\t\t\telse errors.push({ type, errors: parsed.error });\n\t\t}\n\n\t\t// Return all errors if there are any\n\t\tif (errors.length > 0) {\n\t\t\t// If a custom error handler is provided, use it\n\t\t\tif (schemas.handler) return schemas.handler(errors, req, res, next);\n\n\t\t\tres.status(400).send(errors.map(error => ({ type: error.type, errors: error.errors })));\n\t\t\treturn;\n\t\t}\n\n\t\treturn next();\n\t};\n}\n\n/**\n * Describes the types of data that can be validated: 'query', 'params', or 'body'.\n */\ntype DataType = (typeof types)[number];\n\n/**\n * Defines the structure of an error item, containing the type of validation that failed (params, query, or body)\n * and the associated ZodError.\n */\nexport interface ErrorListItem {\n\ttype: DataType;\n\terrors: ZodError;\n}\n\n/**\n * Represents an Express.js error request handler where the params, query and body are of unknown type as validation failed.\n */\nexport type ErrorRequestHandler<\n\tP = unknown,\n\tResBody = any,\n\tReqBody = unknown,\n\tReqQuery = unknown,\n\tLocalsObj extends Record<string, any> = Record<string, any>\n> = (\n\terr: ErrorListItem[],\n\treq: Request<P, ResBody, ReqBody, ReqQuery, LocalsObj>,\n\tres: Response<ResBody, LocalsObj>,\n\tnext: NextFunction\n) => void | Promise<void>;\n\n/**\n * Represents a generic type for route validation, which can be applied to params, query, or body.\n * Each key-value pair represents a field and its corresponding Zod validation schema.\n */\nexport type ValidationSchema = ZodTypeAny | ZodRawShape;\n\n/**\n * Defines the structure for the schemas provided to the validate middleware.\n * Each property corresponds to a different part of the request (params, query, body)\n * and should be a record of Zod types for validation. Optional handler for custom error handling.\n *\n * @template TParams - Type definition for params schema.\n * @template TQuery - Type definition for query schema.\n * @template TBody - Type definition for body schema.\n */\nexport interface CompleteValidationSchema<\n\tTParams extends ValidationSchema = EmptyValidationSchema,\n\tTQuery extends ValidationSchema = EmptyValidationSchema,\n\tTBody extends ValidationSchema = EmptyValidationSchema\n> {\n\thandler?: ErrorRequestHandler;\n\tparams?: TParams;\n\tquery?: TQuery;\n\tbody?: TBody;\n}\n\n/**\n * Represents the output type of a Zod validation schema.\n * This is used to infer the TypeScript type from a Zod schema,\n * providing typesafe access to the validated data.\n *\n * @template T - The validation type (params, query, or body).\n */\nexport type ZodOutput<T extends ValidationSchema> = T extends ZodRawShape ? z.ZodObject<T>['_output'] : T['_output'];\n\n/**\n * A utility type to ensure other middleware types don't conflict with the validate middleware.\n */\nexport type WeakRequestHandler = RequestHandler<unknown, unknown, unknown, Record<string, unknown>>;\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import express from "express";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
var types = ["query", "params", "body"];
|
|
5
|
+
var emptyObjectSchema = z.object({}).strict();
|
|
6
|
+
function isZodSchema(schema) {
|
|
7
|
+
return !!schema && typeof schema.safeParseAsync === "function";
|
|
8
|
+
}
|
|
9
|
+
var descriptor = Object.getOwnPropertyDescriptor(express.request, "query");
|
|
10
|
+
if (descriptor) {
|
|
11
|
+
Object.defineProperty(express.request, "query", {
|
|
12
|
+
get() {
|
|
13
|
+
if (this._query) return this._query;
|
|
14
|
+
return descriptor?.get?.call(this);
|
|
15
|
+
},
|
|
16
|
+
set(query) {
|
|
17
|
+
this._query = query;
|
|
18
|
+
},
|
|
19
|
+
configurable: true,
|
|
20
|
+
enumerable: true
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function validate(schemas) {
|
|
24
|
+
const validation = {
|
|
25
|
+
params: isZodSchema(schemas.params) ? schemas.params : z.object(schemas.params ?? {}).strict(),
|
|
26
|
+
query: isZodSchema(schemas.query) ? schemas.query : z.object(schemas.query ?? {}).strict(),
|
|
27
|
+
body: isZodSchema(schemas.body) ? schemas.body : z.object(schemas.body ?? {}).strict()
|
|
28
|
+
};
|
|
29
|
+
return async (req, res, next) => {
|
|
30
|
+
const errors = [];
|
|
31
|
+
for (const type of types) {
|
|
32
|
+
const parsed = await validation[type].safeParseAsync(req[type] ?? {});
|
|
33
|
+
if (parsed.success) req[type] = parsed.data;
|
|
34
|
+
else errors.push({ type, errors: parsed.error });
|
|
35
|
+
}
|
|
36
|
+
if (errors.length > 0) {
|
|
37
|
+
if (schemas.handler) return schemas.handler(errors, req, res, next);
|
|
38
|
+
res.status(400).send(errors.map((error) => ({ type: error.type, errors: error.errors })));
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
return next();
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export {
|
|
45
|
+
validate as default
|
|
46
|
+
};
|
|
47
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/// <reference types=\"./express.d.ts\" />\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport express from 'express';\nimport { type ZodError, type ZodRawShape, type ZodSchema, type ZodTypeAny, z } from 'zod';\n\nconst types = ['query', 'params', 'body'] as const;\nconst emptyObjectSchema = z.object({}).strict();\nexport type EmptyValidationSchema = typeof emptyObjectSchema;\n\n/**\n * A ZodSchema type guard.\n * @param schema The Zod schema to check.\n * @returns Whether the provided schema is a ZodSchema.\n */\nfunction isZodSchema(schema: unknown): schema is ZodSchema {\n\treturn !!schema && typeof (schema as ZodSchema).safeParseAsync === 'function';\n}\n\n// Override express@^5 request.query getter to provider setter\nconst descriptor = Object.getOwnPropertyDescriptor(express.request, 'query');\nif (descriptor) {\n\tObject.defineProperty(express.request, 'query', {\n\t\tget(this: Request) {\n\t\t\tif (this._query) return this._query;\n\t\t\treturn descriptor?.get?.call(this);\n\t\t},\n\t\tset(this: Request, query: unknown) {\n\t\t\tthis._query = query;\n\t\t},\n\t\tconfigurable: true,\n\t\tenumerable: true\n\t});\n}\n\n/**\n * Generates a middleware function for Express.js that validates request params, query, and body.\n * This function uses Zod schemas to perform validation against the provided schema definitions.\n *\n * @param schemas - An object containing Zod schemas for params, query, and body. Optional handler for custom error handling.\n * @returns An Express.js middleware function that validates the request based on the provided schemas.\n * It attaches validated data to the request object and sends error details if validation fails.\n * @template TParams - Type definition for params schema.\n * @template TQuery - Type definition for query schema.\n * @template TBody - Type definition for body schema.\n * @example\n * // Example usage in an Express.js route\n * import express from 'express';\n * import validate from 'express-zod-safe';\n * import { z } from 'zod';\n *\n * const app = express();\n *\n * // Define your Zod schemas\n * const params = {\n * userId: z.string().uuid(),\n * };\n * const query = {\n * age: z.coerce.number().optional(),\n * };\n * const body = {\n * name: z.string(),\n * email: z.string().email(),\n * };\n *\n * // Use the validate middleware in your route\n * app.post('/user/:userId', validate({ params, query, body }), (req, res) => {\n * // Your route logic here\n * res.send('User data is valid!');\n * });\n *\n * app.listen(3000, () => console.log('Server running on port 3000'));\n */\nexport default function validate<\n\tTParams extends ValidationSchema = EmptyValidationSchema,\n\tTQuery extends ValidationSchema = EmptyValidationSchema,\n\tTBody extends ValidationSchema = EmptyValidationSchema\n>(schemas: CompleteValidationSchema<TParams, TQuery, TBody>): RequestHandler<ZodOutput<TParams>, any, ZodOutput<TBody>, ZodOutput<TQuery>> {\n\t// Create validation objects for each type\n\tconst validation = {\n\t\tparams: isZodSchema(schemas.params) ? schemas.params : z.object(schemas.params ?? {}).strict(),\n\t\tquery: isZodSchema(schemas.query) ? schemas.query : z.object(schemas.query ?? {}).strict(),\n\t\tbody: isZodSchema(schemas.body) ? schemas.body : z.object(schemas.body ?? {}).strict()\n\t};\n\n\treturn async (req, res, next): Promise<void> => {\n\t\tconst errors: ErrorListItem[] = [];\n\n\t\t// Validate all types (params, query, body)\n\t\tfor (const type of types) {\n\t\t\tconst parsed = await validation[type].safeParseAsync(req[type] ?? {});\n\t\t\tif (parsed.success) req[type] = parsed.data;\n\t\t\telse errors.push({ type, errors: parsed.error });\n\t\t}\n\n\t\t// Return all errors if there are any\n\t\tif (errors.length > 0) {\n\t\t\t// If a custom error handler is provided, use it\n\t\t\tif (schemas.handler) return schemas.handler(errors, req, res, next);\n\n\t\t\tres.status(400).send(errors.map(error => ({ type: error.type, errors: error.errors })));\n\t\t\treturn;\n\t\t}\n\n\t\treturn next();\n\t};\n}\n\n/**\n * Describes the types of data that can be validated: 'query', 'params', or 'body'.\n */\ntype DataType = (typeof types)[number];\n\n/**\n * Defines the structure of an error item, containing the type of validation that failed (params, query, or body)\n * and the associated ZodError.\n */\nexport interface ErrorListItem {\n\ttype: DataType;\n\terrors: ZodError;\n}\n\n/**\n * Represents an Express.js error request handler where the params, query and body are of unknown type as validation failed.\n */\nexport type ErrorRequestHandler<\n\tP = unknown,\n\tResBody = any,\n\tReqBody = unknown,\n\tReqQuery = unknown,\n\tLocalsObj extends Record<string, any> = Record<string, any>\n> = (\n\terr: ErrorListItem[],\n\treq: Request<P, ResBody, ReqBody, ReqQuery, LocalsObj>,\n\tres: Response<ResBody, LocalsObj>,\n\tnext: NextFunction\n) => void | Promise<void>;\n\n/**\n * Represents a generic type for route validation, which can be applied to params, query, or body.\n * Each key-value pair represents a field and its corresponding Zod validation schema.\n */\nexport type ValidationSchema = ZodTypeAny | ZodRawShape;\n\n/**\n * Defines the structure for the schemas provided to the validate middleware.\n * Each property corresponds to a different part of the request (params, query, body)\n * and should be a record of Zod types for validation. Optional handler for custom error handling.\n *\n * @template TParams - Type definition for params schema.\n * @template TQuery - Type definition for query schema.\n * @template TBody - Type definition for body schema.\n */\nexport interface CompleteValidationSchema<\n\tTParams extends ValidationSchema = EmptyValidationSchema,\n\tTQuery extends ValidationSchema = EmptyValidationSchema,\n\tTBody extends ValidationSchema = EmptyValidationSchema\n> {\n\thandler?: ErrorRequestHandler;\n\tparams?: TParams;\n\tquery?: TQuery;\n\tbody?: TBody;\n}\n\n/**\n * Represents the output type of a Zod validation schema.\n * This is used to infer the TypeScript type from a Zod schema,\n * providing typesafe access to the validated data.\n *\n * @template T - The validation type (params, query, or body).\n */\nexport type ZodOutput<T extends ValidationSchema> = T extends ZodRawShape ? z.ZodObject<T>['_output'] : T['_output'];\n\n/**\n * A utility type to ensure other middleware types don't conflict with the validate middleware.\n */\nexport type WeakRequestHandler = RequestHandler<unknown, unknown, unknown, Record<string, unknown>>;\n"],"mappings":";AAEA,OAAO,aAAa;AACpB,SAA2E,SAAS;AAEpF,IAAM,QAAQ,CAAC,SAAS,UAAU,MAAM;AACxC,IAAM,oBAAoB,EAAE,OAAO,CAAC,CAAC,EAAE,OAAO;AAQ9C,SAAS,YAAY,QAAsC;AAC1D,SAAO,CAAC,CAAC,UAAU,OAAQ,OAAqB,mBAAmB;AACpE;AAGA,IAAM,aAAa,OAAO,yBAAyB,QAAQ,SAAS,OAAO;AAC3E,IAAI,YAAY;AACf,SAAO,eAAe,QAAQ,SAAS,SAAS;AAAA,IAC/C,MAAmB;AAClB,UAAI,KAAK,OAAQ,QAAO,KAAK;AAC7B,aAAO,YAAY,KAAK,KAAK,IAAI;AAAA,IAClC;AAAA,IACA,IAAmB,OAAgB;AAClC,WAAK,SAAS;AAAA,IACf;AAAA,IACA,cAAc;AAAA,IACd,YAAY;AAAA,EACb,CAAC;AACF;AAwCe,SAAR,SAIL,SAAyI;AAE1I,QAAM,aAAa;AAAA,IAClB,QAAQ,YAAY,QAAQ,MAAM,IAAI,QAAQ,SAAS,EAAE,OAAO,QAAQ,UAAU,CAAC,CAAC,EAAE,OAAO;AAAA,IAC7F,OAAO,YAAY,QAAQ,KAAK,IAAI,QAAQ,QAAQ,EAAE,OAAO,QAAQ,SAAS,CAAC,CAAC,EAAE,OAAO;AAAA,IACzF,MAAM,YAAY,QAAQ,IAAI,IAAI,QAAQ,OAAO,EAAE,OAAO,QAAQ,QAAQ,CAAC,CAAC,EAAE,OAAO;AAAA,EACtF;AAEA,SAAO,OAAO,KAAK,KAAK,SAAwB;AAC/C,UAAM,SAA0B,CAAC;AAGjC,eAAW,QAAQ,OAAO;AACzB,YAAM,SAAS,MAAM,WAAW,IAAI,EAAE,eAAe,IAAI,IAAI,KAAK,CAAC,CAAC;AACpE,UAAI,OAAO,QAAS,KAAI,IAAI,IAAI,OAAO;AAAA,UAClC,QAAO,KAAK,EAAE,MAAM,QAAQ,OAAO,MAAM,CAAC;AAAA,IAChD;AAGA,QAAI,OAAO,SAAS,GAAG;AAEtB,UAAI,QAAQ,QAAS,QAAO,QAAQ,QAAQ,QAAQ,KAAK,KAAK,IAAI;AAElE,UAAI,OAAO,GAAG,EAAE,KAAK,OAAO,IAAI,YAAU,EAAE,MAAM,MAAM,MAAM,QAAQ,MAAM,OAAO,EAAE,CAAC;AACtF;AAAA,IACD;AAEA,WAAO,KAAK;AAAA,EACb;AACD;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,10 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-safe",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.3",
|
|
4
4
|
"description": "TypeScript-friendly middleware designed for Express applications, leveraging the robustness of Zod schemas to validate incoming request bodies, parameters, and queries.",
|
|
5
|
-
"main": "dist/
|
|
6
|
-
"module": "dist/
|
|
7
|
-
"types": "dist/
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": {
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"default": "./dist/index.mjs"
|
|
13
|
+
},
|
|
14
|
+
"require": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
},
|
|
8
20
|
"repository": {
|
|
9
21
|
"type": "git",
|
|
10
22
|
"url": "git+https://github.com/AngaBlue/express-zod-safe.git"
|
|
@@ -28,21 +40,22 @@
|
|
|
28
40
|
},
|
|
29
41
|
"homepage": "https://github.com/AngaBlue/express-zod-safe#readme",
|
|
30
42
|
"devDependencies": {
|
|
31
|
-
"@angablue/biome-config": "^1.0.
|
|
43
|
+
"@angablue/biome-config": "^1.0.5",
|
|
32
44
|
"@biomejs/biome": "^1.9.4",
|
|
33
|
-
"@types/node": "^22.15.
|
|
34
|
-
"
|
|
45
|
+
"@types/node": "^22.15.26",
|
|
46
|
+
"tsup": "^8.5.0",
|
|
35
47
|
"typescript": "^5.8.3",
|
|
36
|
-
"zod": "^3.
|
|
48
|
+
"zod": "^3.25.39"
|
|
37
49
|
},
|
|
38
50
|
"peerDependencies": {
|
|
39
51
|
"@types/express": "^4.0.0 || ^5.0.0",
|
|
40
52
|
"express": "^4.0.0 || ^5.0.0",
|
|
41
53
|
"zod": "^3.0.0"
|
|
42
54
|
},
|
|
55
|
+
"packageManager": "pnpm@10.11.0",
|
|
43
56
|
"scripts": {
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"
|
|
57
|
+
"build": "tsup",
|
|
58
|
+
"lint": "biome check --fix",
|
|
59
|
+
"test": "pnpx tsx ./test/index.ts"
|
|
47
60
|
}
|
|
48
61
|
}
|
package/dist/cjs/index.js
DELETED
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
-
};
|
|
14
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.default = validate;
|
|
16
|
-
const express_1 = __importDefault(require("express"));
|
|
17
|
-
const zod_1 = require("zod");
|
|
18
|
-
const types = ['query', 'params', 'body'];
|
|
19
|
-
const emptyObjectSchema = zod_1.z.object({}).strict();
|
|
20
|
-
/**
|
|
21
|
-
* A ZodSchema type guard.
|
|
22
|
-
* @param schema The Zod schema to check.
|
|
23
|
-
* @returns Whether the provided schema is a ZodSchema.
|
|
24
|
-
*/
|
|
25
|
-
function isZodSchema(schema) {
|
|
26
|
-
return !!schema && typeof schema.safeParseAsync === 'function';
|
|
27
|
-
}
|
|
28
|
-
// Override express@^5 request.query getter to provider setter
|
|
29
|
-
const descriptor = Object.getOwnPropertyDescriptor(express_1.default.request, 'query');
|
|
30
|
-
if (descriptor) {
|
|
31
|
-
Object.defineProperty(express_1.default.request, 'query', {
|
|
32
|
-
get() {
|
|
33
|
-
var _a;
|
|
34
|
-
if (this._query)
|
|
35
|
-
return this._query;
|
|
36
|
-
return (_a = descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) === null || _a === void 0 ? void 0 : _a.call(this);
|
|
37
|
-
},
|
|
38
|
-
set(query) {
|
|
39
|
-
this._query = query;
|
|
40
|
-
},
|
|
41
|
-
configurable: true,
|
|
42
|
-
enumerable: true
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Generates a middleware function for Express.js that validates request params, query, and body.
|
|
47
|
-
* This function uses Zod schemas to perform validation against the provided schema definitions.
|
|
48
|
-
*
|
|
49
|
-
* @param schemas - An object containing Zod schemas for params, query, and body. Optional handler for custom error handling.
|
|
50
|
-
* @returns An Express.js middleware function that validates the request based on the provided schemas.
|
|
51
|
-
* It attaches validated data to the request object and sends error details if validation fails.
|
|
52
|
-
* @template TParams - Type definition for params schema.
|
|
53
|
-
* @template TQuery - Type definition for query schema.
|
|
54
|
-
* @template TBody - Type definition for body schema.
|
|
55
|
-
* @example
|
|
56
|
-
* // Example usage in an Express.js route
|
|
57
|
-
* import express from 'express';
|
|
58
|
-
* import validate from 'express-zod-safe';
|
|
59
|
-
* import { z } from 'zod';
|
|
60
|
-
*
|
|
61
|
-
* const app = express();
|
|
62
|
-
*
|
|
63
|
-
* // Define your Zod schemas
|
|
64
|
-
* const params = {
|
|
65
|
-
* userId: z.string().uuid(),
|
|
66
|
-
* };
|
|
67
|
-
* const query = {
|
|
68
|
-
* age: z.coerce.number().optional(),
|
|
69
|
-
* };
|
|
70
|
-
* const body = {
|
|
71
|
-
* name: z.string(),
|
|
72
|
-
* email: z.string().email(),
|
|
73
|
-
* };
|
|
74
|
-
*
|
|
75
|
-
* // Use the validate middleware in your route
|
|
76
|
-
* app.post('/user/:userId', validate({ params, query, body }), (req, res) => {
|
|
77
|
-
* // Your route logic here
|
|
78
|
-
* res.send('User data is valid!');
|
|
79
|
-
* });
|
|
80
|
-
*
|
|
81
|
-
* app.listen(3000, () => console.log('Server running on port 3000'));
|
|
82
|
-
*/
|
|
83
|
-
function validate(schemas) {
|
|
84
|
-
var _a, _b, _c;
|
|
85
|
-
// Create validation objects for each type
|
|
86
|
-
const validation = {
|
|
87
|
-
params: isZodSchema(schemas.params) ? schemas.params : zod_1.z.object((_a = schemas.params) !== null && _a !== void 0 ? _a : {}).strict(),
|
|
88
|
-
query: isZodSchema(schemas.query) ? schemas.query : zod_1.z.object((_b = schemas.query) !== null && _b !== void 0 ? _b : {}).strict(),
|
|
89
|
-
body: isZodSchema(schemas.body) ? schemas.body : zod_1.z.object((_c = schemas.body) !== null && _c !== void 0 ? _c : {}).strict()
|
|
90
|
-
};
|
|
91
|
-
return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
|
|
92
|
-
var _a;
|
|
93
|
-
const errors = [];
|
|
94
|
-
// Validate all types (params, query, body)
|
|
95
|
-
for (const type of types) {
|
|
96
|
-
const parsed = yield validation[type].safeParseAsync((_a = req[type]) !== null && _a !== void 0 ? _a : {});
|
|
97
|
-
if (parsed.success)
|
|
98
|
-
req[type] = parsed.data;
|
|
99
|
-
else
|
|
100
|
-
errors.push({ type, errors: parsed.error });
|
|
101
|
-
}
|
|
102
|
-
// Return all errors if there are any
|
|
103
|
-
if (errors.length > 0) {
|
|
104
|
-
// If a custom error handler is provided, use it
|
|
105
|
-
if (schemas.handler)
|
|
106
|
-
return schemas.handler(errors, req, res, next);
|
|
107
|
-
res.status(400).send(errors.map(error => ({ type: error.type, errors: error.errors })));
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
return next();
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
module.exports = validate;
|
package/dist/esm/index.js
DELETED
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import express from 'express';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
const types = ['query', 'params', 'body'];
|
|
4
|
-
const emptyObjectSchema = z.object({}).strict();
|
|
5
|
-
/**
|
|
6
|
-
* A ZodSchema type guard.
|
|
7
|
-
* @param schema The Zod schema to check.
|
|
8
|
-
* @returns Whether the provided schema is a ZodSchema.
|
|
9
|
-
*/
|
|
10
|
-
function isZodSchema(schema) {
|
|
11
|
-
return !!schema && typeof schema.safeParseAsync === 'function';
|
|
12
|
-
}
|
|
13
|
-
// Override express@^5 request.query getter to provider setter
|
|
14
|
-
const descriptor = Object.getOwnPropertyDescriptor(express.request, 'query');
|
|
15
|
-
if (descriptor) {
|
|
16
|
-
Object.defineProperty(express.request, 'query', {
|
|
17
|
-
get() {
|
|
18
|
-
if (this._query)
|
|
19
|
-
return this._query;
|
|
20
|
-
return descriptor?.get?.call(this);
|
|
21
|
-
},
|
|
22
|
-
set(query) {
|
|
23
|
-
this._query = query;
|
|
24
|
-
},
|
|
25
|
-
configurable: true,
|
|
26
|
-
enumerable: true
|
|
27
|
-
});
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Generates a middleware function for Express.js that validates request params, query, and body.
|
|
31
|
-
* This function uses Zod schemas to perform validation against the provided schema definitions.
|
|
32
|
-
*
|
|
33
|
-
* @param schemas - An object containing Zod schemas for params, query, and body. Optional handler for custom error handling.
|
|
34
|
-
* @returns An Express.js middleware function that validates the request based on the provided schemas.
|
|
35
|
-
* It attaches validated data to the request object and sends error details if validation fails.
|
|
36
|
-
* @template TParams - Type definition for params schema.
|
|
37
|
-
* @template TQuery - Type definition for query schema.
|
|
38
|
-
* @template TBody - Type definition for body schema.
|
|
39
|
-
* @example
|
|
40
|
-
* // Example usage in an Express.js route
|
|
41
|
-
* import express from 'express';
|
|
42
|
-
* import validate from 'express-zod-safe';
|
|
43
|
-
* import { z } from 'zod';
|
|
44
|
-
*
|
|
45
|
-
* const app = express();
|
|
46
|
-
*
|
|
47
|
-
* // Define your Zod schemas
|
|
48
|
-
* const params = {
|
|
49
|
-
* userId: z.string().uuid(),
|
|
50
|
-
* };
|
|
51
|
-
* const query = {
|
|
52
|
-
* age: z.coerce.number().optional(),
|
|
53
|
-
* };
|
|
54
|
-
* const body = {
|
|
55
|
-
* name: z.string(),
|
|
56
|
-
* email: z.string().email(),
|
|
57
|
-
* };
|
|
58
|
-
*
|
|
59
|
-
* // Use the validate middleware in your route
|
|
60
|
-
* app.post('/user/:userId', validate({ params, query, body }), (req, res) => {
|
|
61
|
-
* // Your route logic here
|
|
62
|
-
* res.send('User data is valid!');
|
|
63
|
-
* });
|
|
64
|
-
*
|
|
65
|
-
* app.listen(3000, () => console.log('Server running on port 3000'));
|
|
66
|
-
*/
|
|
67
|
-
export default function validate(schemas) {
|
|
68
|
-
// Create validation objects for each type
|
|
69
|
-
const validation = {
|
|
70
|
-
params: isZodSchema(schemas.params) ? schemas.params : z.object(schemas.params ?? {}).strict(),
|
|
71
|
-
query: isZodSchema(schemas.query) ? schemas.query : z.object(schemas.query ?? {}).strict(),
|
|
72
|
-
body: isZodSchema(schemas.body) ? schemas.body : z.object(schemas.body ?? {}).strict()
|
|
73
|
-
};
|
|
74
|
-
return async (req, res, next) => {
|
|
75
|
-
const errors = [];
|
|
76
|
-
// Validate all types (params, query, body)
|
|
77
|
-
for (const type of types) {
|
|
78
|
-
const parsed = await validation[type].safeParseAsync(req[type] ?? {});
|
|
79
|
-
if (parsed.success)
|
|
80
|
-
req[type] = parsed.data;
|
|
81
|
-
else
|
|
82
|
-
errors.push({ type, errors: parsed.error });
|
|
83
|
-
}
|
|
84
|
-
// Return all errors if there are any
|
|
85
|
-
if (errors.length > 0) {
|
|
86
|
-
// If a custom error handler is provided, use it
|
|
87
|
-
if (schemas.handler)
|
|
88
|
-
return schemas.handler(errors, req, res, next);
|
|
89
|
-
res.status(400).send(errors.map(error => ({ type: error.type, errors: error.errors })));
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
return next();
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
module.exports = validate;
|