express-zod-safe 1.0.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/LICENSE ADDED
@@ -0,0 +1,165 @@
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.
package/README.md ADDED
@@ -0,0 +1,109 @@
1
+ <h1 align="center">🛡️ Express Zod Safe</h1>
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">
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" />
8
+ </a>
9
+ </p>
10
+
11
+ Express Zod Safe is a strict, typesafe middleware designed for Node.js applications, leveraging the robustness of Zod schemas to validate incoming request bodies, parameters, and queries. This package seamlessly integrates with Express.js (or similar frameworks) to provide developers with a typesafe, declarative approach to ensure data integrity and prevent invalid or malicious data from affecting their applications.
12
+
13
+ ### 🏠 [Homepage](https://github.com/AngaBlue/express-zod-safe)
14
+
15
+ ## 🔒 Features
16
+
17
+ - **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.
19
+ - **Middleware Flexibility**: Easily integrates with Express.js middleware stack, ensuring a smooth validation process without compromising performance.
20
+ - **Parameter & Query Validation**: Validates not just request bodies but also URL parameters and query strings, covering all facets of incoming data.
21
+ - **Error Handling**: Provides detailed, developer-friendly error responses to aid in debugging and informing API consumers.
22
+ - **Simple & Intuitive**: Designed to be easy to use and understand, with a declarative API that is both concise and powerful.
23
+
24
+ ## ⬇️ Install
25
+
26
+ Install this package using your package manager of choice.
27
+
28
+ ```sh
29
+ npm i express-zod-safe
30
+ ```
31
+
32
+ `zod`, `express` and `@types/express` are peer dependencies and must be installed separately. This means you can bring your own version of these packages, and this package will not force you to use a specific version.
33
+
34
+ ```sh
35
+ npm i zod express && npm i -D @types/express
36
+ ```
37
+
38
+ ## 🛠️ Usage
39
+
40
+ ```ts
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(), // Given all query params and url params are strings, this will coerce the value to a number.
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
+
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
+
70
+ ### ⚠️ URL Parameters & Query Strings Coercion
71
+ 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
+
73
+ ```ts
74
+ const params = {
75
+ userId: z.coerce.number(),
76
+ };
77
+
78
+ app.get('/user/:userId', validate({ params }), (req, res) => {
79
+ // req.params.userId -> number
80
+ });
81
+ ```
82
+
83
+ ### ⚠️ Missing Validation Schemas
84
+ 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.
85
+
86
+ ```ts
87
+ const body = {
88
+ name: z.string(),
89
+ email: z.string().email(),
90
+ };
91
+
92
+ app.post('/user', validate({ body }), (req, res) => {
93
+ // req.body.name -> string
94
+ // req.body.email -> string
95
+ // req.params.age -> undefined
96
+ // req.query.age -> undefined
97
+ });
98
+ ```
99
+
100
+ 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.
101
+
102
+ ## ⭐️ Show your support
103
+
104
+ Give a ⭐️ if this project helped you!
105
+
106
+ ## 📝 License
107
+
108
+ Copyright © [AngaBlue](https://github.com/AngaBlue).<br />
109
+ This project is [LGPL--3.0--or--later](https://github.com/AngaBlue/express-zod-safe/blob/master/LICENSE) licensed.
@@ -0,0 +1,69 @@
1
+ import { RequestHandler } from 'express';
2
+ import { z } from 'zod';
3
+ /**
4
+ * Generates a middleware function for Express.js that validates request params, query, and body.
5
+ * This function uses Zod schemas to perform validation against the provided schema definitions.
6
+ *
7
+ * @param schemas - An object containing Zod schemas for params, query, and body.
8
+ * @returns An Express.js middleware function that validates the request based on the provided schemas.
9
+ * It attaches validated data to the request object and sends error details if validation fails.
10
+ * @template TParams - Type definition for params schema.
11
+ * @template TQuery - Type definition for query schema.
12
+ * @template TBody - Type definition for body schema.
13
+ * @example
14
+ * // Example usage in an Express.js route
15
+ * import express from 'express';
16
+ * import validate from 'express-zod-safe';
17
+ * import { z } from 'zod';
18
+ *
19
+ * const app = express();
20
+ *
21
+ * // Define your Zod schemas
22
+ * const params = {
23
+ * userId: z.string().uuid(),
24
+ * };
25
+ * const query = {
26
+ * age: z.coerce.number().optional(),
27
+ * };
28
+ * const body = {
29
+ * name: z.string(),
30
+ * email: z.string().email(),
31
+ * };
32
+ *
33
+ * // Use the validate middleware in your route
34
+ * app.post('/user/:userId', validate({ params, query, body }), (req, res) => {
35
+ * // Your route logic here
36
+ * res.send('User data is valid!');
37
+ * });
38
+ *
39
+ * app.listen(3000, () => console.log('Server running on port 3000'));
40
+ */
41
+ declare function validate<TParams extends Validation = {}, TQuery extends Validation = {}, TBody extends Validation = {}>(schemas: ValidationSchemas<TParams, TQuery, TBody>): RequestHandler<ZodOutput<TParams>, any, ZodOutput<TBody>, ZodOutput<TQuery>>;
42
+ /**
43
+ * Represents a generic type for route validation, which can be applied to params, query, or body.
44
+ * Each key-value pair represents a field and its corresponding Zod validation schema.
45
+ */
46
+ type Validation = Record<string, z.ZodTypeAny>;
47
+ /**
48
+ * Defines the structure for the schemas provided to the validate middleware.
49
+ * Each property corresponds to a different part of the request (params, query, body)
50
+ * and should be a record of Zod types for validation.
51
+ *
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
+ */
56
+ interface ValidationSchemas<TParams extends Validation, TQuery extends Validation, TBody extends Validation> {
57
+ params?: TParams;
58
+ query?: TQuery;
59
+ body?: TBody;
60
+ }
61
+ /**
62
+ * Represents the output type of a Zod validation schema.
63
+ * This is used to infer the TypeScript type from a Zod schema,
64
+ * providing typesafe access to the validated data.
65
+ *
66
+ * @template T - The validation type (params, query, or body).
67
+ */
68
+ type ZodOutput<T extends Validation> = z.ZodObject<T>['_output'];
69
+ export = validate;
package/dist/index.js ADDED
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ const zod_1 = require("zod");
3
+ const types = ['query', 'params', 'body'];
4
+ /**
5
+ * Generates a middleware function for Express.js that validates request params, query, and body.
6
+ * This function uses Zod schemas to perform validation against the provided schema definitions.
7
+ *
8
+ * @param schemas - An object containing Zod schemas for params, query, and body.
9
+ * @returns An Express.js middleware function that validates the request based on the provided schemas.
10
+ * It attaches validated data to the request object and sends error details if validation fails.
11
+ * @template TParams - Type definition for params schema.
12
+ * @template TQuery - Type definition for query schema.
13
+ * @template TBody - Type definition for body schema.
14
+ * @example
15
+ * // Example usage in an Express.js route
16
+ * import express from 'express';
17
+ * import validate from 'express-zod-safe';
18
+ * import { z } from 'zod';
19
+ *
20
+ * const app = express();
21
+ *
22
+ * // Define your Zod schemas
23
+ * const params = {
24
+ * userId: z.string().uuid(),
25
+ * };
26
+ * const query = {
27
+ * age: z.coerce.number().optional(),
28
+ * };
29
+ * const body = {
30
+ * name: z.string(),
31
+ * email: z.string().email(),
32
+ * };
33
+ *
34
+ * // Use the validate middleware in your route
35
+ * app.post('/user/:userId', validate({ params, query, body }), (req, res) => {
36
+ * // Your route logic here
37
+ * res.send('User data is valid!');
38
+ * });
39
+ *
40
+ * app.listen(3000, () => console.log('Server running on port 3000'));
41
+ */
42
+ function validate(schemas) {
43
+ var _a, _b, _c;
44
+ // Create validation objects for each type
45
+ const validation = {
46
+ params: zod_1.z.object((_a = schemas.params) !== null && _a !== void 0 ? _a : {}).strict(),
47
+ query: zod_1.z.object((_b = schemas.query) !== null && _b !== void 0 ? _b : {}).strict(),
48
+ body: zod_1.z.object((_c = schemas.body) !== null && _c !== void 0 ? _c : {}).strict()
49
+ };
50
+ return (req, res, next) => {
51
+ const errors = [];
52
+ // Validate all types (params, query, body)
53
+ for (const type of types) {
54
+ const parsed = validation[type].safeParse(req[type]);
55
+ // @ts-expect-error This is fine
56
+ if (parsed.success)
57
+ req[type] = parsed.data;
58
+ else
59
+ errors.push({ type, errors: parsed.error });
60
+ }
61
+ // Return all errors if there are any
62
+ if (errors.length > 0)
63
+ return res.status(400).send(errors.map(error => ({ type: error.type, errors: error.errors })));
64
+ return next();
65
+ };
66
+ }
67
+ module.exports = validate;
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "express-zod-safe",
3
+ "version": "1.0.0",
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",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/AngaBlue/exe.git"
9
+ },
10
+ "keywords": [
11
+ "zod",
12
+ "express",
13
+ "middleware",
14
+ "validation",
15
+ "guard",
16
+ "typesafe"
17
+ ],
18
+ "author": "AngaBlue <contact@anga.blue>",
19
+ "license": "LGPL-3.0-or-later",
20
+ "bugs": {
21
+ "url": "https://github.com/AngaBlue/exe/issues"
22
+ },
23
+ "homepage": "https://github.com/AngaBlue/exe#readme",
24
+ "devDependencies": {
25
+ "@angablue/eslint-config": "^1.4.4",
26
+ "@types/node": "^20.10.7",
27
+ "eslint": "^8.56.0",
28
+ "express": "^4.18.2",
29
+ "prettier": "^3.1.1",
30
+ "rimraf": "^5.0.5",
31
+ "typescript": "^5.3.3",
32
+ "zod": "^3.22.4"
33
+ },
34
+ "peerDependencies": {
35
+ "@types/express": "^4.0.0",
36
+ "express": "^4.0.0",
37
+ "zod": "^3.0.0"
38
+ },
39
+ "scripts": {
40
+ "clean": "rimraf dist",
41
+ "build": "pnpm run clean && tsc",
42
+ "lint": "eslint . --ext js,jsx,ts,tsx --fix"
43
+ }
44
+ }