express-zod-safe 1.4.0 → 1.5.1

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/LICENSE CHANGED
@@ -1,165 +1,21 @@
1
- GNU LESSER GENERAL PUBLIC LICENSE
2
- Version 3, 29 June 2007
3
-
4
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
- Everyone is permitted to copy and distribute verbatim copies
6
- of this license document, but changing it is not allowed.
7
-
8
-
9
- This version of the GNU Lesser General Public License incorporates
10
- the terms and conditions of version 3 of the GNU General Public
11
- License, supplemented by the additional permissions listed below.
12
-
13
- 0. Additional Definitions.
14
-
15
- As used herein, "this License" refers to version 3 of the GNU Lesser
16
- General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
- General Public License.
18
-
19
- "The Library" refers to a covered work governed by this License,
20
- other than an Application or a Combined Work as defined below.
21
-
22
- An "Application" is any work that makes use of an interface provided
23
- by the Library, but which is not otherwise based on the Library.
24
- Defining a subclass of a class defined by the Library is deemed a mode
25
- of using an interface provided by the Library.
26
-
27
- A "Combined Work" is a work produced by combining or linking an
28
- Application with the Library. The particular version of the Library
29
- with which the Combined Work was made is also called the "Linked
30
- Version".
31
-
32
- The "Minimal Corresponding Source" for a Combined Work means the
33
- Corresponding Source for the Combined Work, excluding any source code
34
- for portions of the Combined Work that, considered in isolation, are
35
- based on the Application, and not on the Linked Version.
36
-
37
- The "Corresponding Application Code" for a Combined Work means the
38
- object code and/or source code for the Application, including any data
39
- and utility programs needed for reproducing the Combined Work from the
40
- Application, but excluding the System Libraries of the Combined Work.
41
-
42
- 1. Exception to Section 3 of the GNU GPL.
43
-
44
- You may convey a covered work under sections 3 and 4 of this License
45
- without being bound by section 3 of the GNU GPL.
46
-
47
- 2. Conveying Modified Versions.
48
-
49
- If you modify a copy of the Library, and, in your modifications, a
50
- facility refers to a function or data to be supplied by an Application
51
- that uses the facility (other than as an argument passed when the
52
- facility is invoked), then you may convey a copy of the modified
53
- version:
54
-
55
- a) under this License, provided that you make a good faith effort to
56
- ensure that, in the event an Application does not supply the
57
- function or data, the facility still operates, and performs
58
- whatever part of its purpose remains meaningful, or
59
-
60
- b) under the GNU GPL, with none of the additional permissions of
61
- this License applicable to that copy.
62
-
63
- 3. Object Code Incorporating Material from Library Header Files.
64
-
65
- The object code form of an Application may incorporate material from
66
- a header file that is part of the Library. You may convey such object
67
- code under terms of your choice, provided that, if the incorporated
68
- material is not limited to numerical parameters, data structure
69
- layouts and accessors, or small macros, inline functions and templates
70
- (ten or fewer lines in length), you do both of the following:
71
-
72
- a) Give prominent notice with each copy of the object code that the
73
- Library is used in it and that the Library and its use are
74
- covered by this License.
75
-
76
- b) Accompany the object code with a copy of the GNU GPL and this license
77
- document.
78
-
79
- 4. Combined Works.
80
-
81
- You may convey a Combined Work under terms of your choice that,
82
- taken together, effectively do not restrict modification of the
83
- portions of the Library contained in the Combined Work and reverse
84
- engineering for debugging such modifications, if you also do each of
85
- the following:
86
-
87
- a) Give prominent notice with each copy of the Combined Work that
88
- the Library is used in it and that the Library and its use are
89
- covered by this License.
90
-
91
- b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
- document.
93
-
94
- c) For a Combined Work that displays copyright notices during
95
- execution, include the copyright notice for the Library among
96
- these notices, as well as a reference directing the user to the
97
- copies of the GNU GPL and this license document.
98
-
99
- d) Do one of the following:
100
-
101
- 0) Convey the Minimal Corresponding Source under the terms of this
102
- License, and the Corresponding Application Code in a form
103
- suitable for, and under terms that permit, the user to
104
- recombine or relink the Application with a modified version of
105
- the Linked Version to produce a modified Combined Work, in the
106
- manner specified by section 6 of the GNU GPL for conveying
107
- Corresponding Source.
108
-
109
- 1) Use a suitable shared library mechanism for linking with the
110
- Library. A suitable mechanism is one that (a) uses at run time
111
- a copy of the Library already present on the user's computer
112
- system, and (b) will operate properly with a modified version
113
- of the Library that is interface-compatible with the Linked
114
- Version.
115
-
116
- e) Provide Installation Information, but only if you would otherwise
117
- be required to provide such information under section 6 of the
118
- GNU GPL, and only to the extent that such information is
119
- necessary to install and execute a modified version of the
120
- Combined Work produced by recombining or relinking the
121
- Application with a modified version of the Linked Version. (If
122
- you use option 4d0, the Installation Information must accompany
123
- the Minimal Corresponding Source and Corresponding Application
124
- Code. If you use option 4d1, you must provide the Installation
125
- Information in the manner specified by section 6 of the GNU GPL
126
- for conveying Corresponding Source.)
127
-
128
- 5. Combined Libraries.
129
-
130
- You may place library facilities that are a work based on the
131
- Library side by side in a single library together with other library
132
- facilities that are not Applications and are not covered by this
133
- License, and convey such a combined library under terms of your
134
- choice, if you do both of the following:
135
-
136
- a) Accompany the combined library with a copy of the same work based
137
- on the Library, uncombined with any other library facilities,
138
- conveyed under the terms of this License.
139
-
140
- b) Give prominent notice with the combined library that part of it
141
- is a work based on the Library, and explaining where to find the
142
- accompanying uncombined form of the same work.
143
-
144
- 6. Revised Versions of the GNU Lesser General Public License.
145
-
146
- The Free Software Foundation may publish revised and/or new versions
147
- of the GNU Lesser General Public License from time to time. Such new
148
- versions will be similar in spirit to the present version, but may
149
- differ in detail to address new problems or concerns.
150
-
151
- Each version is given a distinguishing version number. If the
152
- Library as you received it specifies that a certain numbered version
153
- of the GNU Lesser General Public License "or any later version"
154
- applies to it, you have the option of following the terms and
155
- conditions either of that published version or of any later version
156
- published by the Free Software Foundation. If the Library as you
157
- received it does not specify a version number of the GNU Lesser
158
- General Public License, you may choose any version of the GNU Lesser
159
- General Public License ever published by the Free Software Foundation.
160
-
161
- If the Library as you received it specifies that a proxy can decide
162
- whether future versions of the GNU Lesser General Public License shall
163
- apply, that proxy's public statement of acceptance of any version is
164
- permanent authorization for you to choose that version for the
165
- Library.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 AngaBlue
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,10 +1,13 @@
1
1
  <h1 align="center">🛡️ Express Zod Safe</h1>
2
2
  <p align="center">
3
- <a href="https://www.npmjs.com/package/express-zod-safe" target="_blank">
4
- <img alt="GitHub tag (latest by date)" src="https://img.shields.io/github/v/tag/AngaBlue/express-zod-safe?label=Version">
3
+ <a href="https://www.npmjs.com/package/express-zod-safe" target="_blank">
4
+ <img alt="Downloads" src="https://img.shields.io/npm/dm/express-zod-safe.svg?color=blue&?label=Downloads">
5
5
  </a>
6
- <a href="https://github.com/AngaBlue/express-zod-safe/blob/master/LICENSE" target="_blank">
7
- <img alt="License: LGPL--3.0--or--later" src="https://img.shields.io/github/license/AngaBlue/express-zod-safe?color=green" />
6
+ <a href="https://www.npmjs.com/package/express-zod-safe" target="_blank">
7
+ <img alt="Version" src="https://img.shields.io/npm/v/express-zod-safe.svg?label=Version">
8
+ </a>
9
+ <a href="https://github.com/AngaBlue/exe/blob/master/LICENSE" target="_blank">
10
+ <img alt="License: MIT" src="https://img.shields.io/npm/l/express-zod-safe?color=green?label=Licence" />
8
11
  </a>
9
12
  </p>
10
13
 
@@ -15,7 +18,7 @@ _This package was inspired by Aquila169's [zod-express-middleware](https://githu
15
18
  ## 🔒 Features
16
19
 
17
20
  - **Typesafe**: Built with TypeScript, offering complete typesafe interfaces that enrich your development experience.
18
- - **Zod Integration**: Utilizes Zod schemas for comprehensive and customizable request validation.
21
+ - **Zod Integration**: Utilises Zod schemas for comprehensive and customisable request validation.
19
22
  - **Middleware Flexibility**: Easily integrates with Express.js middleware stack, ensuring a smooth validation process without compromising performance.
20
23
  - **Parameter & Query Validation**: Validates not just request bodies but also URL parameters and query strings, covering all facets of incoming data.
21
24
  - **Error Handling**: Provides detailed, developer-friendly error responses to aid in debugging and informing API consumers.
@@ -68,7 +71,7 @@ app.listen(3000, () => console.log('Server running on port 3000'));
68
71
  **Note:** The `validate` middleware must be used **after** any other middleware that parses/modifies the request body, such as `express.json()` or `express.urlencoded()`.
69
72
 
70
73
  ### 📦 Custom Error Handling
71
- By default, the `validate` middleware will send a 400 Bad Request response with a JSON body containing the error message. However, you can provide your own error handling function to customize the error response.
74
+ By default, the `validate` middleware will send a 400 Bad Request response with a JSON body containing the error message. However, you can provide your own error handling function to customise the error response.
72
75
 
73
76
  ```ts
74
77
  // ... extending the previous example
@@ -87,6 +90,40 @@ app.post('/user/:userId', validate({ handler, params, query, body }), (req, res)
87
90
  });
88
91
  ```
89
92
 
93
+ ### ⚠️ Usage with Additional Middleware
94
+ When using `express-zod-safe` with other middleware, it is important not to explicitly type the `Request` parameter in the middleware, as this will override the inferred type that `express-zod-safe` generates from your validation schemas. The best way to do this is to instead type your other middleware (or cast them) to `WeakRequestHandler`, a weakly typed version of the `RequestHandler` type from `express`.
95
+
96
+ ```ts
97
+ import validate, { type WeakRequestHandler } from 'express-zod-safe';
98
+
99
+ // Use the RequestHandler type, instead of explicitly typing (req: Request, res: Response, next: NextFunction)
100
+ const authenticate: WeakRequestHandler = (req, res, next) => {
101
+ // ... perform user authentication
102
+
103
+ next();
104
+ };
105
+
106
+ app.post('/user/:userId', authenticate, validate({ params, query, body }), (req, res) => {
107
+ // Your validation typing will work as expected here
108
+ });
109
+
110
+ ```
111
+
112
+ If you do not control the middleware, such as when you import it from another library, you can instead cast the middleware to `WeakRequestHandler`.
113
+
114
+ ```ts
115
+ // For one off cases...
116
+ app.post('/user/:userId', authenticate as WeakRequestHandler, validate({ params, query, body }), (req, res) => {
117
+ // Your validation typing will work as expected here
118
+ });
119
+
120
+ // For a middleware with a lot of use, aliasing the middleware...
121
+ const auth = authenticate as WeakRequestHandler;
122
+ app.post('/user/:userId', auth, validate({ params, query, body }), (req, res) => {
123
+ // Your validation typing will work as expected here
124
+ });
125
+ ```
126
+
90
127
  ### ⚠️ URL Parameters & Query Strings Coercion
91
128
  As mentioned in the example above, all URL parameters and query strings are parsed as strings. This means that if you have a URL parameter or query string that is expected to be a number, you must use the `z.coerce.number()` method to coerce the value to a number. This is because Zod will not coerce the value for you, and will instead throw an error if the value is not a string.
92
129
 
@@ -101,7 +138,7 @@ app.get('/user/:userId', validate({ params }), (req, res) => {
101
138
  ```
102
139
 
103
140
  ### ⚠️ Missing Validation Schemas
104
- If you do not provide a validation schema for a particular request component (e.g. `params`, `query`, or `body`), then that component will be assumed to be empty. This means that requests with non-empty components will be rejected, and requests with empty components will be accepted. The types on the `req` object will also reflect this, and will be `undefined` if the component is not provided.
141
+ If you do not provide a validation schema for a particular request component (e.g. `params`, `query`, or `body`), then that component will be assumed to be empty. This means that requests with non-empty components will be rejected, and requests with empty components will be accepted. The types on the `req` object will also reflect this, and will be an empty object `{}` if the component is not provided.
105
142
 
106
143
  ```ts
107
144
  const body = {
@@ -112,12 +149,28 @@ const body = {
112
149
  app.post('/user', validate({ body }), (req, res) => {
113
150
  // req.body.name -> string
114
151
  // req.body.email -> string
115
- // req.params.age -> undefined
116
- // req.query.age -> undefined
152
+ // req.params.age -> Property 'age' does not exist on type '{}'
153
+ // req.query.age -> Property 'age' does not exist on type '{}'
117
154
  });
118
155
  ```
119
156
 
120
- This behaviour is intentional and ensures that you do not try to access or use a property that does not exist on the `req` object.
157
+ This behaviour is intentional and ensures that you do not try to access or use a property that does not exist on the `req` object. If you'd prefer to allow any property for any given request component, you can do so by setting a loose validation schema with `z.any()`.
158
+
159
+ ```ts
160
+ const body = {
161
+ name: z.string(),
162
+ email: z.string().email(),
163
+ };
164
+
165
+ const params = z.any()
166
+
167
+ app.post('/user', validate({ body, params }), (req, res) => {
168
+ // req.body.name -> string
169
+ // req.body.email -> string
170
+ // req.params.age -> any
171
+ // req.query.age -> Property 'age' does not exist on type '{}'
172
+ });
173
+ ```
121
174
 
122
175
  ## ⭐️ Show your support
123
176
 
@@ -126,4 +179,4 @@ Give a ⭐️ on GitHub if this project helped you!
126
179
  ## 📝 License
127
180
 
128
181
  Copyright © [AngaBlue](https://github.com/AngaBlue).<br />
129
- This project is [LGPL--3.0--or--later](https://github.com/AngaBlue/express-zod-safe/blob/master/LICENSE) licensed.
182
+ This project is [MIT](https://github.com/AngaBlue/express-zod-safe/blob/master/LICENSE) licensed.
@@ -11,6 +11,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.default = validate;
14
16
  const express_1 = __importDefault(require("express"));
15
17
  const zod_1 = require("zod");
16
18
  const types = ['query', 'params', 'body'];
@@ -2,7 +2,7 @@ import type { NextFunction, Request, RequestHandler, Response } from 'express';
2
2
  import { type ZodError, type ZodRawShape, type ZodTypeAny, z } from 'zod';
3
3
  declare const types: readonly ["query", "params", "body"];
4
4
  declare const emptyObjectSchema: z.ZodObject<{}, "strict", ZodTypeAny, {}, {}>;
5
- type Empty = typeof emptyObjectSchema;
5
+ export type EmptyValidationSchema = typeof emptyObjectSchema;
6
6
  /**
7
7
  * Generates a middleware function for Express.js that validates request params, query, and body.
8
8
  * This function uses Zod schemas to perform validation against the provided schema definitions.
@@ -41,7 +41,7 @@ type Empty = typeof emptyObjectSchema;
41
41
  *
42
42
  * app.listen(3000, () => console.log('Server running on port 3000'));
43
43
  */
44
- declare function validate<TParams extends Validation = Empty, TQuery extends Validation = Empty, TBody extends Validation = Empty>(schemas: ExtendedValidationSchemas<TParams, TQuery, TBody>): RequestHandler<ZodOutput<TParams>, any, ZodOutput<TBody>, ZodOutput<TQuery>>;
44
+ export default 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
45
  /**
46
46
  * Describes the types of data that can be validated: 'query', 'params', or 'body'.
47
47
  */
@@ -50,25 +50,19 @@ type DataType = (typeof types)[number];
50
50
  * Defines the structure of an error item, containing the type of validation that failed (params, query, or body)
51
51
  * and the associated ZodError.
52
52
  */
53
- interface ErrorListItem {
53
+ export interface ErrorListItem {
54
54
  type: DataType;
55
55
  errors: ZodError;
56
56
  }
57
57
  /**
58
- * Represents a QueryString object parsed by the qs library.
58
+ * Represents an Express.js error request handler where the params, query and body are of unknown type as validation failed.
59
59
  */
60
- interface ParsedQs {
61
- [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[];
62
- }
63
- /**
64
- * Represents an Express.js error request handler.
65
- */
66
- type ErrorRequestHandler<P = Record<string, string>, ResBody = any, ReqBody = any, ReqQuery = ParsedQs, 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>;
60
+ export 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>;
67
61
  /**
68
62
  * Represents a generic type for route validation, which can be applied to params, query, or body.
69
63
  * Each key-value pair represents a field and its corresponding Zod validation schema.
70
64
  */
71
- type Validation = ZodTypeAny | ZodRawShape;
65
+ export type ValidationSchema = ZodTypeAny | ZodRawShape;
72
66
  /**
73
67
  * Defines the structure for the schemas provided to the validate middleware.
74
68
  * Each property corresponds to a different part of the request (params, query, body)
@@ -78,7 +72,7 @@ type Validation = ZodTypeAny | ZodRawShape;
78
72
  * @template TQuery - Type definition for query schema.
79
73
  * @template TBody - Type definition for body schema.
80
74
  */
81
- interface ExtendedValidationSchemas<TParams, TQuery, TBody> {
75
+ export interface CompleteValidationSchema<TParams extends ValidationSchema = EmptyValidationSchema, TQuery extends ValidationSchema = EmptyValidationSchema, TBody extends ValidationSchema = EmptyValidationSchema> {
82
76
  handler?: ErrorRequestHandler;
83
77
  params?: TParams;
84
78
  query?: TQuery;
@@ -91,5 +85,9 @@ interface ExtendedValidationSchemas<TParams, TQuery, TBody> {
91
85
  *
92
86
  * @template T - The validation type (params, query, or body).
93
87
  */
94
- type ZodOutput<T extends Validation> = T extends ZodRawShape ? z.ZodObject<T>['_output'] : T['_output'];
95
- export = validate;
88
+ export type ZodOutput<T extends ValidationSchema> = T extends ZodRawShape ? z.ZodObject<T>['_output'] : T['_output'];
89
+ /**
90
+ * A utility type to ensure other middleware types don't conflict with the validate middleware.
91
+ */
92
+ export type WeakRequestHandler = RequestHandler<unknown, unknown, unknown, Record<string, unknown>>;
93
+ export {};
@@ -0,0 +1,95 @@
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;
package/package.json CHANGED
@@ -1,8 +1,10 @@
1
1
  {
2
2
  "name": "express-zod-safe",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
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/index.js",
5
+ "main": "dist/cjs/index.js",
6
+ "module": "dist/esm/index.js",
7
+ "types": "dist/esm/index.d.ts",
6
8
  "repository": {
7
9
  "type": "git",
8
10
  "url": "git+https://github.com/AngaBlue/express-zod-safe.git"
@@ -15,8 +17,12 @@
15
17
  "guard",
16
18
  "typesafe"
17
19
  ],
18
- "author": "AngaBlue <contact@anga.blue>",
19
- "license": "LGPL-3.0-or-later",
20
+ "author": {
21
+ "name": "AngaBlue",
22
+ "email": "contact@anga.blue",
23
+ "url": "https://anga.blue"
24
+ },
25
+ "license": "MIT",
20
26
  "bugs": {
21
27
  "url": "https://github.com/AngaBlue/express-zod-safe/issues"
22
28
  },
@@ -36,7 +42,7 @@
36
42
  },
37
43
  "scripts": {
38
44
  "clean": "rimraf dist",
39
- "build": "pnpm run clean && tsc",
40
- "lint": "biome check --fix --error-on-warnings"
45
+ "build": "pnpm run clean && tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json",
46
+ "lint": "biome check --fix"
41
47
  }
42
48
  }