express-zod-safe 1.1.2 → 1.2.0
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 +20 -0
- package/dist/index.d.ts +28 -4
- package/dist/index.js +8 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -67,6 +67,26 @@ app.listen(3000, () => console.log('Server running on port 3000'));
|
|
|
67
67
|
|
|
68
68
|
**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
69
|
|
|
70
|
+
### 📦 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.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
// ... extending the previous example
|
|
75
|
+
|
|
76
|
+
const handler = (errors, req, res, next) => {
|
|
77
|
+
return res.status(400).json({
|
|
78
|
+
message: 'Invalid request data',
|
|
79
|
+
errors: errors.map((error) => error.message),
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// Use the validate middleware in your route
|
|
84
|
+
app.post('/user/:userId', validate({ handler, params, query, body }), (req, res) => {
|
|
85
|
+
// Your route logic here
|
|
86
|
+
res.send('User data is valid!');
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
70
90
|
### ⚠️ URL Parameters & Query Strings Coercion
|
|
71
91
|
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.
|
|
72
92
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { RequestHandler } from 'express';
|
|
2
|
-
import { z, ZodTypeAny, ZodRawShape } from 'zod';
|
|
1
|
+
import { NextFunction, Request, RequestHandler, Response } from 'express';
|
|
2
|
+
import { ZodError, z, ZodTypeAny, ZodRawShape } from 'zod';
|
|
3
|
+
declare const types: readonly ["query", "params", "body"];
|
|
3
4
|
/**
|
|
4
5
|
* Generates a middleware function for Express.js that validates request params, query, and body.
|
|
5
6
|
* This function uses Zod schemas to perform validation against the provided schema definitions.
|
|
6
7
|
*
|
|
7
|
-
* @param schemas - An object containing Zod schemas for params, query, and body.
|
|
8
|
+
* @param schemas - An object containing Zod schemas for params, query, and body. Optional handler for custom error handling.
|
|
8
9
|
* @returns An Express.js middleware function that validates the request based on the provided schemas.
|
|
9
10
|
* It attaches validated data to the request object and sends error details if validation fails.
|
|
10
11
|
* @template TParams - Type definition for params schema.
|
|
@@ -39,6 +40,28 @@ import { z, ZodTypeAny, ZodRawShape } from 'zod';
|
|
|
39
40
|
* app.listen(3000, () => console.log('Server running on port 3000'));
|
|
40
41
|
*/
|
|
41
42
|
declare function validate<TParams extends Validation = {}, TQuery extends Validation = {}, TBody extends Validation = {}>(schemas: ExtendedValidationSchemas<TParams, TQuery, TBody>): RequestHandler<ZodOutput<TParams>, any, ZodOutput<TBody>, ZodOutput<TQuery>>;
|
|
43
|
+
/**
|
|
44
|
+
* Describes the types of data that can be validated: 'query', 'params', or 'body'.
|
|
45
|
+
*/
|
|
46
|
+
type DataType = (typeof types)[number];
|
|
47
|
+
/**
|
|
48
|
+
* Defines the structure of an error item, containing the type of validation that failed (params, query, or body)
|
|
49
|
+
* and the associated ZodError.
|
|
50
|
+
*/
|
|
51
|
+
interface ErrorListItem {
|
|
52
|
+
type: DataType;
|
|
53
|
+
errors: ZodError<any>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Represents a QueryString object parsed by the qs library.
|
|
57
|
+
*/
|
|
58
|
+
interface ParsedQs {
|
|
59
|
+
[key: string]: undefined | string | string[] | ParsedQs | ParsedQs[];
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Represents an Express.js error request handler.
|
|
63
|
+
*/
|
|
64
|
+
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;
|
|
42
65
|
/**
|
|
43
66
|
* Represents a generic type for route validation, which can be applied to params, query, or body.
|
|
44
67
|
* Each key-value pair represents a field and its corresponding Zod validation schema.
|
|
@@ -47,13 +70,14 @@ type Validation = ZodTypeAny | ZodRawShape;
|
|
|
47
70
|
/**
|
|
48
71
|
* Defines the structure for the schemas provided to the validate middleware.
|
|
49
72
|
* Each property corresponds to a different part of the request (params, query, body)
|
|
50
|
-
* and should be a record of Zod types for validation.
|
|
73
|
+
* and should be a record of Zod types for validation. Optional handler for custom error handling.
|
|
51
74
|
*
|
|
52
75
|
* @template TParams - Type definition for params schema.
|
|
53
76
|
* @template TQuery - Type definition for query schema.
|
|
54
77
|
* @template TBody - Type definition for body schema.
|
|
55
78
|
*/
|
|
56
79
|
interface ExtendedValidationSchemas<TParams, TQuery, TBody> {
|
|
80
|
+
handler?: ErrorRequestHandler;
|
|
57
81
|
params?: TParams;
|
|
58
82
|
query?: TQuery;
|
|
59
83
|
body?: TBody;
|
package/dist/index.js
CHANGED
|
@@ -13,7 +13,7 @@ function isZodSchema(schema) {
|
|
|
13
13
|
* Generates a middleware function for Express.js that validates request params, query, and body.
|
|
14
14
|
* This function uses Zod schemas to perform validation against the provided schema definitions.
|
|
15
15
|
*
|
|
16
|
-
* @param schemas - An object containing Zod schemas for params, query, and body.
|
|
16
|
+
* @param schemas - An object containing Zod schemas for params, query, and body. Optional handler for custom error handling.
|
|
17
17
|
* @returns An Express.js middleware function that validates the request based on the provided schemas.
|
|
18
18
|
* It attaches validated data to the request object and sends error details if validation fails.
|
|
19
19
|
* @template TParams - Type definition for params schema.
|
|
@@ -56,18 +56,23 @@ function validate(schemas) {
|
|
|
56
56
|
body: isZodSchema(schemas.body) ? schemas.body : zod_1.z.object((_c = schemas.body) !== null && _c !== void 0 ? _c : {}).strict()
|
|
57
57
|
};
|
|
58
58
|
return (req, res, next) => {
|
|
59
|
+
var _a;
|
|
59
60
|
const errors = [];
|
|
60
61
|
// Validate all types (params, query, body)
|
|
61
62
|
for (const type of types) {
|
|
62
|
-
const parsed = validation[type].safeParse(req[type]);
|
|
63
|
+
const parsed = validation[type].safeParse((_a = req[type]) !== null && _a !== void 0 ? _a : {});
|
|
63
64
|
if (parsed.success)
|
|
64
65
|
req[type] = parsed.data;
|
|
65
66
|
else
|
|
66
67
|
errors.push({ type, errors: parsed.error });
|
|
67
68
|
}
|
|
68
69
|
// Return all errors if there are any
|
|
69
|
-
if (errors.length > 0)
|
|
70
|
+
if (errors.length > 0) {
|
|
71
|
+
// If a custom error handler is provided, use it
|
|
72
|
+
if (schemas.handler)
|
|
73
|
+
return schemas.handler(errors, req, res, next);
|
|
70
74
|
return res.status(400).send(errors.map(error => ({ type: error.type, errors: error.errors })));
|
|
75
|
+
}
|
|
71
76
|
return next();
|
|
72
77
|
};
|
|
73
78
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-safe",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
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
5
|
"main": "dist/index.js",
|
|
6
6
|
"repository": {
|