@bram-dc/fastify-type-provider-zod 3.1.2 → 5.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 +21 -21
- package/README.md +280 -148
- package/dist/index.d.ts +2 -86
- package/dist/index.js +14 -159
- package/dist/src/core.d.ts +11 -31
- package/dist/src/core.js +32 -12
- package/dist/src/errors.d.ts +23 -6
- package/dist/src/errors.js +23 -10
- package/package.json +61 -62
- package/dist/src/ResponseValidationError.d.ts +0 -10
- package/dist/src/ResponseValidationError.js +0 -15
- package/dist/src/ref.d.ts +0 -3
- package/dist/src/ref.js +0 -56
- package/dist/src/zod-to-json.d.ts +0 -7
- package/dist/src/zod-to-json.js +0 -12
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2022 turkerdev
|
|
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.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022-2024 turkerdev
|
|
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,148 +1,280 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
app.
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
},
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
import
|
|
50
|
-
|
|
51
|
-
import
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
app.
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
})
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
1
|
+
# Fastify Type Provider Zod
|
|
2
|
+
|
|
3
|
+
[](https://npmjs.org/package/fastify-type-provider-zod)
|
|
4
|
+
[](https://npmjs.org/package/fastify-type-provider-zod)
|
|
5
|
+
[](https://github.com//turkerdev/fastify-type-provider-zod/actions)
|
|
6
|
+
|
|
7
|
+
## How to use?
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
import Fastify from "fastify";
|
|
11
|
+
import { serializerCompiler, validatorCompiler, ZodTypeProvider } from "fastify-type-provider-zod";
|
|
12
|
+
import z from "zod";
|
|
13
|
+
|
|
14
|
+
const app = Fastify()
|
|
15
|
+
|
|
16
|
+
// Add schema validator and serializer
|
|
17
|
+
app.setValidatorCompiler(validatorCompiler);
|
|
18
|
+
app.setSerializerCompiler(serializerCompiler);
|
|
19
|
+
|
|
20
|
+
app.withTypeProvider<ZodTypeProvider>().route({
|
|
21
|
+
method: "GET",
|
|
22
|
+
url: "/",
|
|
23
|
+
// Define your schema
|
|
24
|
+
schema: {
|
|
25
|
+
querystring: z.object({
|
|
26
|
+
name: z.string().min(4),
|
|
27
|
+
}),
|
|
28
|
+
response: {
|
|
29
|
+
200: z.string(),
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
handler: (req, res) => {
|
|
33
|
+
res.send(req.query.name);
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
app.listen({ port: 4949 });
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
You can also pass options to the `serializerCompiler` function:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
type ZodSerializerCompilerOptions = {
|
|
44
|
+
replacer?: ReplacerFunction;
|
|
45
|
+
};
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
import Fastify from 'fastify';
|
|
50
|
+
import { createSerializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
|
|
51
|
+
import z from 'zod';
|
|
52
|
+
|
|
53
|
+
const app = Fastify();
|
|
54
|
+
|
|
55
|
+
const replacer = function (key, value) {
|
|
56
|
+
if (this[key] instanceof Date) {
|
|
57
|
+
return { _date: value.toISOString() };
|
|
58
|
+
}
|
|
59
|
+
return value;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// Create a custom serializer compiler
|
|
63
|
+
const customSerializerCompiler = createSerializerCompiler({ replacer });
|
|
64
|
+
|
|
65
|
+
// Add schema validator and serializer
|
|
66
|
+
app.setValidatorCompiler(validatorCompiler);
|
|
67
|
+
app.setSerializerCompiler(customSerializerCompiler);
|
|
68
|
+
|
|
69
|
+
// ...
|
|
70
|
+
|
|
71
|
+
app.listen({ port: 4949 });
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## How to use together with @fastify/swagger
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import fastify from 'fastify';
|
|
78
|
+
import fastifySwagger from '@fastify/swagger';
|
|
79
|
+
import fastifySwaggerUI from '@fastify/swagger-ui';
|
|
80
|
+
import { z } from 'zod';
|
|
81
|
+
|
|
82
|
+
import {
|
|
83
|
+
jsonSchemaTransform,
|
|
84
|
+
createJsonSchemaTransform,
|
|
85
|
+
serializerCompiler,
|
|
86
|
+
validatorCompiler,
|
|
87
|
+
ZodTypeProvider,
|
|
88
|
+
} from 'fastify-type-provider-zod';
|
|
89
|
+
|
|
90
|
+
const app = fastify();
|
|
91
|
+
app.setValidatorCompiler(validatorCompiler);
|
|
92
|
+
app.setSerializerCompiler(serializerCompiler);
|
|
93
|
+
|
|
94
|
+
app.register(fastifySwagger, {
|
|
95
|
+
openapi: {
|
|
96
|
+
info: {
|
|
97
|
+
title: 'SampleApi',
|
|
98
|
+
description: 'Sample backend service',
|
|
99
|
+
version: '1.0.0',
|
|
100
|
+
},
|
|
101
|
+
servers: [],
|
|
102
|
+
},
|
|
103
|
+
transform: jsonSchemaTransform,
|
|
104
|
+
|
|
105
|
+
// You can also create transform with custom skiplist of endpoints that should not be included in the specification:
|
|
106
|
+
//
|
|
107
|
+
// transform: createJsonSchemaTransform({
|
|
108
|
+
// skipList: [ '/documentation/static/*' ]
|
|
109
|
+
// })
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
app.register(fastifySwaggerUI, {
|
|
113
|
+
routePrefix: '/documentation',
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
const LOGIN_SCHEMA = z.object({
|
|
117
|
+
username: z.string().max(32).describe('Some description for username'),
|
|
118
|
+
password: z.string().max(32),
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
app.after(() => {
|
|
122
|
+
app.withTypeProvider<ZodTypeProvider>().route({
|
|
123
|
+
method: 'POST',
|
|
124
|
+
url: '/login',
|
|
125
|
+
schema: { body: LOGIN_SCHEMA },
|
|
126
|
+
handler: (req, res) => {
|
|
127
|
+
res.send('ok');
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
async function run() {
|
|
133
|
+
await app.ready();
|
|
134
|
+
|
|
135
|
+
await app.listen({
|
|
136
|
+
port: 4949,
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
console.log(`Documentation running at http://localhost:4949/documentation`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
run();
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Customizing error responses
|
|
146
|
+
|
|
147
|
+
You can add custom handling of request and response validation errors to your fastify error handler like this:
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod'
|
|
151
|
+
|
|
152
|
+
fastifyApp.setErrorHandler((err, req, reply) => {
|
|
153
|
+
if (hasZodFastifySchemaValidationErrors(err)) {
|
|
154
|
+
return reply.code(400).send({
|
|
155
|
+
error: 'Response Validation Error',
|
|
156
|
+
message: "Request doesn't match the schema",
|
|
157
|
+
statusCode: 400,
|
|
158
|
+
details: {
|
|
159
|
+
issues: err.validation,
|
|
160
|
+
method: req.method,
|
|
161
|
+
url: req.url,
|
|
162
|
+
},
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (isResponseSerializationError(err)) {
|
|
167
|
+
return reply.code(500).send({
|
|
168
|
+
error: 'Internal Server Error',
|
|
169
|
+
message: "Response doesn't match the schema",
|
|
170
|
+
statusCode: 500,
|
|
171
|
+
details: {
|
|
172
|
+
issues: err.cause.issues,
|
|
173
|
+
method: err.method,
|
|
174
|
+
url: err.url,
|
|
175
|
+
},
|
|
176
|
+
})
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// the rest of the error handler
|
|
180
|
+
})
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## How to create refs to the schemas?
|
|
184
|
+
|
|
185
|
+
When provided, this package will automatically create refs using the `jsonSchemaTransformObject` function. You register the schemas to the global zod registry and give it an `id` and fastifySwagger will create a OpenAPI document in which the schemas are referenced. The following example creates a ref to the `User` schema and will include the `User` schema in the OpenAPI document.
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import fastifySwagger from '@fastify/swagger';
|
|
189
|
+
import fastifySwaggerUI from '@fastify/swagger-ui';
|
|
190
|
+
import fastify from 'fastify';
|
|
191
|
+
import { z } from 'zod';
|
|
192
|
+
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
|
|
193
|
+
import {
|
|
194
|
+
jsonSchemaTransformObject,
|
|
195
|
+
jsonSchemaTransform,
|
|
196
|
+
serializerCompiler,
|
|
197
|
+
validatorCompiler,
|
|
198
|
+
} from 'fastify-type-provider-zod';
|
|
199
|
+
|
|
200
|
+
const USER_SCHEMA = z.object({
|
|
201
|
+
id: z.number().int().positive(),
|
|
202
|
+
name: z.string().describe('The name of the user'),
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
z.globalRegistry.add(USER_SCHEMA, { id: 'User' })
|
|
206
|
+
|
|
207
|
+
const app = fastify();
|
|
208
|
+
app.setValidatorCompiler(validatorCompiler);
|
|
209
|
+
app.setSerializerCompiler(serializerCompiler);
|
|
210
|
+
|
|
211
|
+
app.register(fastifySwagger, {
|
|
212
|
+
openapi: {
|
|
213
|
+
info: {
|
|
214
|
+
title: 'SampleApi',
|
|
215
|
+
description: 'Sample backend service',
|
|
216
|
+
version: '1.0.0',
|
|
217
|
+
},
|
|
218
|
+
servers: [],
|
|
219
|
+
},
|
|
220
|
+
transform: jsonSchemaTransform,
|
|
221
|
+
transformObject: jsonSchemaTransformObject,
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
app.register(fastifySwaggerUI, {
|
|
225
|
+
routePrefix: '/documentation',
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
app.after(() => {
|
|
229
|
+
app.withTypeProvider<ZodTypeProvider>().route({
|
|
230
|
+
method: 'GET',
|
|
231
|
+
url: '/users',
|
|
232
|
+
schema: {
|
|
233
|
+
response: {
|
|
234
|
+
200: USER_SCHEMA.array(),
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
handler: (req, res) => {
|
|
238
|
+
res.send([]);
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
async function run() {
|
|
244
|
+
await app.ready();
|
|
245
|
+
|
|
246
|
+
await app.listen({
|
|
247
|
+
port: 4949,
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
console.log(`Documentation running at http://localhost:4949/documentation`);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
run();
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
## How to create a plugin?
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
import { z } from 'zod';
|
|
260
|
+
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
|
|
261
|
+
|
|
262
|
+
const plugin: FastifyPluginAsyncZod = async function (fastify, _opts) {
|
|
263
|
+
fastify.route({
|
|
264
|
+
method: 'GET',
|
|
265
|
+
url: '/',
|
|
266
|
+
// Define your schema
|
|
267
|
+
schema: {
|
|
268
|
+
querystring: z.object({
|
|
269
|
+
name: z.string().min(4),
|
|
270
|
+
}),
|
|
271
|
+
response: {
|
|
272
|
+
200: z.string(),
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
handler: (req, res) => {
|
|
276
|
+
res.send(req.query.name);
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
};
|
|
280
|
+
```
|
package/dist/index.d.ts
CHANGED
|
@@ -1,86 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import type { FastifySerializerCompiler } from "fastify/types/schema";
|
|
4
|
-
import type { z } from "zod";
|
|
5
|
-
type FreeformRecord = Record<string, any>;
|
|
6
|
-
export declare const ResponseValidationError: import("@fastify/error").FastifyErrorConstructor<{
|
|
7
|
-
code: string;
|
|
8
|
-
}, [{
|
|
9
|
-
cause: Error;
|
|
10
|
-
}]>;
|
|
11
|
-
export declare const InvalidSchemaError: import("@fastify/error").FastifyErrorConstructor<{
|
|
12
|
-
code: string;
|
|
13
|
-
}, [string]>;
|
|
14
|
-
export interface ZodTypeProvider extends FastifyTypeProvider {
|
|
15
|
-
validator: this["schema"] extends z.ZodTypeAny ? z.output<this["schema"]> : unknown;
|
|
16
|
-
serializer: this["schema"] extends z.ZodTypeAny ? z.input<this["schema"]> : unknown;
|
|
17
|
-
}
|
|
18
|
-
interface Schema extends FastifySchema {
|
|
19
|
-
hide?: boolean;
|
|
20
|
-
}
|
|
21
|
-
export declare const createJsonSchemaTransform: ({ skipList }: {
|
|
22
|
-
skipList: readonly string[];
|
|
23
|
-
}) => ({ schema, url }: {
|
|
24
|
-
schema: Schema;
|
|
25
|
-
url: string;
|
|
26
|
-
}) => {
|
|
27
|
-
schema: Schema;
|
|
28
|
-
url: string;
|
|
29
|
-
} | {
|
|
30
|
-
schema: FreeformRecord;
|
|
31
|
-
url: string;
|
|
32
|
-
};
|
|
33
|
-
export declare const jsonSchemaTransform: ({ schema, url }: {
|
|
34
|
-
schema: Schema;
|
|
35
|
-
url: string;
|
|
36
|
-
}) => {
|
|
37
|
-
schema: Schema;
|
|
38
|
-
url: string;
|
|
39
|
-
} | {
|
|
40
|
-
schema: FreeformRecord;
|
|
41
|
-
url: string;
|
|
42
|
-
};
|
|
43
|
-
export declare const ZodValidatorCompiler: FastifySchemaCompiler<z.ZodAny>;
|
|
44
|
-
type ReplacerFunction = (this: any, key: string, value: any) => any;
|
|
45
|
-
type ZodSerializerCompilerOptions = {
|
|
46
|
-
replacer?: ReplacerFunction;
|
|
47
|
-
};
|
|
48
|
-
export declare const createZodSerializerCompiler: (options: ZodSerializerCompilerOptions) => FastifySerializerCompiler<z.ZodAny | {
|
|
49
|
-
properties: z.ZodAny;
|
|
50
|
-
}>;
|
|
51
|
-
export declare const ZodSerializerCompiler: FastifySerializerCompiler<z.ZodAny | {
|
|
52
|
-
properties: z.ZodAny;
|
|
53
|
-
}>;
|
|
54
|
-
export declare const createJsonSchemaTransformObject: ({ schemas: zodSchemas }: {
|
|
55
|
-
schemas: Record<string, z.ZodTypeAny>;
|
|
56
|
-
}) => (input: {
|
|
57
|
-
swaggerObject: Partial<OpenAPIV2.Document>;
|
|
58
|
-
} | {
|
|
59
|
-
openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>;
|
|
60
|
-
}) => any;
|
|
61
|
-
/**
|
|
62
|
-
* FastifyPluginCallbackZod with Zod automatic type inference
|
|
63
|
-
*
|
|
64
|
-
* @example
|
|
65
|
-
* ```typescript
|
|
66
|
-
* import { FastifyPluginCallbackZod } from "fastify-type-provider-zod"
|
|
67
|
-
*
|
|
68
|
-
* const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {
|
|
69
|
-
* done()
|
|
70
|
-
* }
|
|
71
|
-
* ```
|
|
72
|
-
*/
|
|
73
|
-
export type FastifyPluginCallbackZod<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault> = FastifyPluginCallback<Options, Server, ZodTypeProvider>;
|
|
74
|
-
/**
|
|
75
|
-
* FastifyPluginAsyncZod with Zod automatic type inference
|
|
76
|
-
*
|
|
77
|
-
* @example
|
|
78
|
-
* ```typescript
|
|
79
|
-
* import { FastifyPluginAsyncZod } from "fastify-type-provider-zod"
|
|
80
|
-
*
|
|
81
|
-
* const plugin: FastifyPluginAsyncZod = async (fastify, options) => {
|
|
82
|
-
* }
|
|
83
|
-
* ```
|
|
84
|
-
*/
|
|
85
|
-
export type FastifyPluginAsyncZod<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault> = FastifyPluginAsync<Options, Server, ZodTypeProvider>;
|
|
86
|
-
export {};
|
|
1
|
+
export { type ZodTypeProvider, type FastifyPluginAsyncZod, type FastifyPluginCallbackZod, type ZodSerializerCompilerOptions, jsonSchemaTransform, createJsonSchemaTransform, jsonSchemaTransformObject, createJsonSchemaTransformObject, serializerCompiler, validatorCompiler, createSerializerCompiler, } from './src/core';
|
|
2
|
+
export { type ZodFastifySchemaValidationError, ResponseSerializationError, InvalidSchemaError, hasZodFastifySchemaValidationErrors, isResponseSerializationError, } from './src/errors';
|
package/dist/index.js
CHANGED
|
@@ -1,161 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const zodToJsonSchemaOptions = {
|
|
21
|
-
target: "openApi3",
|
|
22
|
-
$refStrategy: "none",
|
|
23
|
-
};
|
|
24
|
-
const createJsonSchemaTransform = ({ skipList }) => {
|
|
25
|
-
return ({ schema, url }) => {
|
|
26
|
-
if (!schema) {
|
|
27
|
-
return {
|
|
28
|
-
schema,
|
|
29
|
-
url,
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
const { response, headers, querystring, body, params, hide, ...rest } = schema;
|
|
33
|
-
const transformed = {};
|
|
34
|
-
if (skipList.includes(url) || hide) {
|
|
35
|
-
transformed.hide = true;
|
|
36
|
-
return { schema: transformed, url };
|
|
37
|
-
}
|
|
38
|
-
const zodSchemas = { headers, querystring, body, params };
|
|
39
|
-
for (const prop in zodSchemas) {
|
|
40
|
-
const zodSchema = zodSchemas[prop];
|
|
41
|
-
if (zodSchema) {
|
|
42
|
-
transformed[prop] = (0, zod_to_json_schema_1.zodToJsonSchema)(zodSchema, zodToJsonSchemaOptions);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
if (response) {
|
|
46
|
-
transformed.response = {};
|
|
47
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
48
|
-
for (const prop in response) {
|
|
49
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
50
|
-
const schema = resolveSchema(response[prop]);
|
|
51
|
-
const transformedResponse = (0, zod_to_json_schema_1.zodToJsonSchema)(
|
|
52
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
53
|
-
schema, zodToJsonSchemaOptions);
|
|
54
|
-
transformed.response[prop] = transformedResponse;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
for (const prop in rest) {
|
|
58
|
-
const meta = rest[prop];
|
|
59
|
-
if (meta) {
|
|
60
|
-
transformed[prop] = meta;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
return { schema: transformed, url };
|
|
64
|
-
};
|
|
65
|
-
};
|
|
66
|
-
exports.createJsonSchemaTransform = createJsonSchemaTransform;
|
|
67
|
-
exports.jsonSchemaTransform = (0, exports.createJsonSchemaTransform)({
|
|
68
|
-
skipList: defaultSkipList,
|
|
69
|
-
});
|
|
70
|
-
const ZodValidatorCompiler = ({ schema }) => (data) => {
|
|
71
|
-
const result = schema.safeParse(data);
|
|
72
|
-
if (result.success) {
|
|
73
|
-
return { value: result.data };
|
|
74
|
-
}
|
|
75
|
-
else {
|
|
76
|
-
return {
|
|
77
|
-
error: result.error.errors.map(error => ({
|
|
78
|
-
keyword: error.code,
|
|
79
|
-
instancePath: `/${error.path.join("/")}`,
|
|
80
|
-
schemaPath: `#/${error.path.join("/")}/${error.code}`,
|
|
81
|
-
params: {
|
|
82
|
-
code: error.code,
|
|
83
|
-
zodError: result.error,
|
|
84
|
-
},
|
|
85
|
-
message: error.message,
|
|
86
|
-
})),
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
exports.ZodValidatorCompiler = ZodValidatorCompiler;
|
|
91
|
-
const resolveSchema = (maybeSchema) => {
|
|
92
|
-
if ("safeParse" in maybeSchema) {
|
|
93
|
-
return maybeSchema;
|
|
94
|
-
}
|
|
95
|
-
if ("properties" in maybeSchema) {
|
|
96
|
-
return maybeSchema.properties;
|
|
97
|
-
}
|
|
98
|
-
throw new exports.InvalidSchemaError(JSON.stringify(maybeSchema));
|
|
99
|
-
};
|
|
100
|
-
const createZodSerializerCompiler = (options) => ({ schema: maybeSchema }) => (data) => {
|
|
101
|
-
const schema = resolveSchema(maybeSchema);
|
|
102
|
-
const result = schema.safeParse(data);
|
|
103
|
-
if (result.success) {
|
|
104
|
-
return JSON.stringify(result.data, options.replacer);
|
|
105
|
-
}
|
|
106
|
-
throw new exports.ResponseValidationError({ cause: result.error });
|
|
107
|
-
};
|
|
108
|
-
exports.createZodSerializerCompiler = createZodSerializerCompiler;
|
|
109
|
-
exports.ZodSerializerCompiler = (0, exports.createZodSerializerCompiler)({});
|
|
110
|
-
const createJsonSchemaTransformObject = ({ schemas: zodSchemas }) => (input) => {
|
|
111
|
-
if ("swaggerObject" in input) {
|
|
112
|
-
console.warn("This package currently does not support component references for Swagger 2.0");
|
|
113
|
-
return input.swaggerObject;
|
|
114
|
-
}
|
|
115
|
-
const schemas = {};
|
|
116
|
-
for (const key in zodSchemas) {
|
|
117
|
-
schemas[key] = (0, zod_to_json_schema_1.zodToJsonSchema)(zodSchemas[key], zodToJsonSchemaOptions);
|
|
118
|
-
}
|
|
119
|
-
const document = {
|
|
120
|
-
...input.openapiObject,
|
|
121
|
-
components: {
|
|
122
|
-
...input.openapiObject.components,
|
|
123
|
-
schemas: {
|
|
124
|
-
...input.openapiObject.components?.schemas,
|
|
125
|
-
...schemas,
|
|
126
|
-
},
|
|
127
|
-
},
|
|
128
|
-
};
|
|
129
|
-
const componentMapVK = new Map();
|
|
130
|
-
Object.entries(schemas).forEach(([key, value]) => componentMapVK.set(JSON.stringify(value), key));
|
|
131
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
132
|
-
function componentReplacer(key, value) {
|
|
133
|
-
if (typeof value !== "object") {
|
|
134
|
-
return value;
|
|
135
|
-
}
|
|
136
|
-
// Check if the parent is the schemas object, if so, return the value as is
|
|
137
|
-
if (this === document.components.schemas) {
|
|
138
|
-
return value;
|
|
139
|
-
}
|
|
140
|
-
const stringifiedValue = JSON.stringify(value);
|
|
141
|
-
if (componentMapVK.has(stringifiedValue)) {
|
|
142
|
-
return { $ref: `#/components/schemas/${componentMapVK.get(stringifiedValue)}` };
|
|
143
|
-
}
|
|
144
|
-
if (value.nullable === true) {
|
|
145
|
-
const nonNullableValue = { ...value };
|
|
146
|
-
delete nonNullableValue.nullable;
|
|
147
|
-
const stringifiedNonNullableValue = JSON.stringify(nonNullableValue);
|
|
148
|
-
if (componentMapVK.has(stringifiedNonNullableValue)) {
|
|
149
|
-
return {
|
|
150
|
-
anyOf: [
|
|
151
|
-
{ $ref: `#/components/schemas/${componentMapVK.get(stringifiedNonNullableValue)}` },
|
|
152
|
-
],
|
|
153
|
-
nullable: true,
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
return value;
|
|
158
|
-
}
|
|
159
|
-
return JSON.parse(JSON.stringify(document, componentReplacer));
|
|
160
|
-
};
|
|
161
|
-
exports.createJsonSchemaTransformObject = createJsonSchemaTransformObject;
|
|
3
|
+
exports.isResponseSerializationError = exports.hasZodFastifySchemaValidationErrors = exports.InvalidSchemaError = exports.ResponseSerializationError = exports.createSerializerCompiler = exports.validatorCompiler = exports.serializerCompiler = exports.createJsonSchemaTransformObject = exports.jsonSchemaTransformObject = exports.createJsonSchemaTransform = exports.jsonSchemaTransform = void 0;
|
|
4
|
+
var core_1 = require("./src/core");
|
|
5
|
+
Object.defineProperty(exports, "jsonSchemaTransform", { enumerable: true, get: function () { return core_1.jsonSchemaTransform; } });
|
|
6
|
+
Object.defineProperty(exports, "createJsonSchemaTransform", { enumerable: true, get: function () { return core_1.createJsonSchemaTransform; } });
|
|
7
|
+
Object.defineProperty(exports, "jsonSchemaTransformObject", { enumerable: true, get: function () { return core_1.jsonSchemaTransformObject; } });
|
|
8
|
+
Object.defineProperty(exports, "createJsonSchemaTransformObject", { enumerable: true, get: function () { return core_1.createJsonSchemaTransformObject; } });
|
|
9
|
+
Object.defineProperty(exports, "serializerCompiler", { enumerable: true, get: function () { return core_1.serializerCompiler; } });
|
|
10
|
+
Object.defineProperty(exports, "validatorCompiler", { enumerable: true, get: function () { return core_1.validatorCompiler; } });
|
|
11
|
+
Object.defineProperty(exports, "createSerializerCompiler", { enumerable: true, get: function () { return core_1.createSerializerCompiler; } });
|
|
12
|
+
var errors_1 = require("./src/errors");
|
|
13
|
+
Object.defineProperty(exports, "ResponseSerializationError", { enumerable: true, get: function () { return errors_1.ResponseSerializationError; } });
|
|
14
|
+
Object.defineProperty(exports, "InvalidSchemaError", { enumerable: true, get: function () { return errors_1.InvalidSchemaError; } });
|
|
15
|
+
Object.defineProperty(exports, "hasZodFastifySchemaValidationErrors", { enumerable: true, get: function () { return errors_1.hasZodFastifySchemaValidationErrors; } });
|
|
16
|
+
Object.defineProperty(exports, "isResponseSerializationError", { enumerable: true, get: function () { return errors_1.isResponseSerializationError; } });
|
package/dist/src/core.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
+
import type { SwaggerTransform, SwaggerTransformObject } from '@fastify/swagger';
|
|
1
2
|
import type { FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifySchema, FastifySchemaCompiler, FastifyTypeProvider, RawServerBase, RawServerDefault } from 'fastify';
|
|
2
3
|
import type { FastifySerializerCompiler } from 'fastify/types/schema';
|
|
3
|
-
import
|
|
4
|
-
import type { z } from 'zod';
|
|
5
|
-
type FreeformRecord = Record<string, any>;
|
|
4
|
+
import { z } from 'zod';
|
|
6
5
|
export interface ZodTypeProvider extends FastifyTypeProvider {
|
|
7
6
|
validator: this['schema'] extends z.ZodTypeAny ? z.output<this['schema']> : unknown;
|
|
8
7
|
serializer: this['schema'] extends z.ZodTypeAny ? z.input<this['schema']> : unknown;
|
|
@@ -10,44 +9,25 @@ export interface ZodTypeProvider extends FastifyTypeProvider {
|
|
|
10
9
|
interface Schema extends FastifySchema {
|
|
11
10
|
hide?: boolean;
|
|
12
11
|
}
|
|
13
|
-
|
|
12
|
+
type CreateJsonSchemaTransformOptions = {
|
|
14
13
|
skipList: readonly string[];
|
|
15
|
-
}) => ({ schema, url }: {
|
|
16
|
-
schema: Schema;
|
|
17
|
-
url: string;
|
|
18
|
-
}) => {
|
|
19
|
-
schema: Schema;
|
|
20
|
-
url: string;
|
|
21
|
-
} | {
|
|
22
|
-
schema: FreeformRecord;
|
|
23
|
-
url: string;
|
|
24
14
|
};
|
|
25
|
-
export declare const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
schema: Schema;
|
|
30
|
-
url: string;
|
|
31
|
-
} | {
|
|
32
|
-
schema: FreeformRecord;
|
|
33
|
-
url: string;
|
|
15
|
+
export declare const createJsonSchemaTransform: ({ skipList, }: CreateJsonSchemaTransformOptions) => SwaggerTransform<Schema>;
|
|
16
|
+
export declare const jsonSchemaTransform: SwaggerTransform<Schema>;
|
|
17
|
+
type CreateJsonSchemaTransformObjectOptions = {
|
|
18
|
+
schemaRegistry: z.core.$ZodJSONSchemaRegistry;
|
|
34
19
|
};
|
|
35
|
-
export declare const createJsonSchemaTransformObject: ({
|
|
36
|
-
|
|
37
|
-
}) => (input: {
|
|
38
|
-
swaggerObject: Partial<OpenAPIV2.Document>;
|
|
39
|
-
} | {
|
|
40
|
-
openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>;
|
|
41
|
-
}) => any;
|
|
20
|
+
export declare const createJsonSchemaTransformObject: ({ schemaRegistry }: CreateJsonSchemaTransformObjectOptions) => SwaggerTransformObject;
|
|
21
|
+
export declare const jsonSchemaTransformObject: SwaggerTransformObject;
|
|
42
22
|
export declare const validatorCompiler: FastifySchemaCompiler<z.ZodTypeAny>;
|
|
43
23
|
type ReplacerFunction = (this: any, key: string, value: any) => any;
|
|
44
|
-
type ZodSerializerCompilerOptions = {
|
|
24
|
+
export type ZodSerializerCompilerOptions = {
|
|
45
25
|
replacer?: ReplacerFunction;
|
|
46
26
|
};
|
|
47
27
|
export declare const createSerializerCompiler: (options?: ZodSerializerCompilerOptions) => FastifySerializerCompiler<z.ZodTypeAny | {
|
|
48
28
|
properties: z.ZodTypeAny;
|
|
49
29
|
}>;
|
|
50
|
-
export declare const serializerCompiler: FastifySerializerCompiler<z.
|
|
30
|
+
export declare const serializerCompiler: FastifySerializerCompiler<z.ZodType<unknown, unknown> | {
|
|
51
31
|
properties: z.ZodTypeAny;
|
|
52
32
|
}>;
|
|
53
33
|
/**
|
package/dist/src/core.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.serializerCompiler = exports.createSerializerCompiler = exports.validatorCompiler = exports.createJsonSchemaTransformObject = exports.jsonSchemaTransform = exports.createJsonSchemaTransform = void 0;
|
|
3
|
+
exports.serializerCompiler = exports.createSerializerCompiler = exports.validatorCompiler = exports.jsonSchemaTransformObject = exports.createJsonSchemaTransformObject = exports.jsonSchemaTransform = exports.createJsonSchemaTransform = void 0;
|
|
4
|
+
const zod_1 = require("zod");
|
|
4
5
|
const errors_1 = require("./errors");
|
|
5
|
-
const ref_1 = require("./ref");
|
|
6
|
-
const zod_to_json_1 = require("./zod-to-json");
|
|
7
6
|
const defaultSkipList = [
|
|
8
7
|
'/documentation/',
|
|
9
8
|
'/documentation/initOAuth',
|
|
@@ -13,7 +12,15 @@ const defaultSkipList = [
|
|
|
13
12
|
'/documentation/*',
|
|
14
13
|
'/documentation/static/*',
|
|
15
14
|
];
|
|
16
|
-
const
|
|
15
|
+
const zodtoJSONSchemaOptions = {
|
|
16
|
+
uri: (id) => `#/components/schemas/${id}`,
|
|
17
|
+
external: {
|
|
18
|
+
registry: zod_1.z.globalRegistry,
|
|
19
|
+
uri: (id) => `#/components/schemas/${id}`,
|
|
20
|
+
defs: {},
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
const createJsonSchemaTransform = ({ skipList, }) => {
|
|
17
24
|
return ({ schema, url }) => {
|
|
18
25
|
if (!schema) {
|
|
19
26
|
return {
|
|
@@ -31,7 +38,7 @@ const createJsonSchemaTransform = ({ skipList }) => {
|
|
|
31
38
|
for (const prop in zodSchemas) {
|
|
32
39
|
const zodSchema = zodSchemas[prop];
|
|
33
40
|
if (zodSchema) {
|
|
34
|
-
transformed[prop] = (
|
|
41
|
+
transformed[prop] = zod_1.z.toJSONSchema(zodSchema, zodtoJSONSchemaOptions);
|
|
35
42
|
}
|
|
36
43
|
}
|
|
37
44
|
if (response) {
|
|
@@ -39,8 +46,8 @@ const createJsonSchemaTransform = ({ skipList }) => {
|
|
|
39
46
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
40
47
|
for (const prop in response) {
|
|
41
48
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
42
|
-
const
|
|
43
|
-
const transformedResponse = (
|
|
49
|
+
const zodSchema = resolveSchema(response[prop]);
|
|
50
|
+
const transformedResponse = zod_1.z.toJSONSchema(zodSchema, zodtoJSONSchemaOptions);
|
|
44
51
|
transformed.response[prop] = transformedResponse;
|
|
45
52
|
}
|
|
46
53
|
}
|
|
@@ -57,18 +64,31 @@ exports.createJsonSchemaTransform = createJsonSchemaTransform;
|
|
|
57
64
|
exports.jsonSchemaTransform = (0, exports.createJsonSchemaTransform)({
|
|
58
65
|
skipList: defaultSkipList,
|
|
59
66
|
});
|
|
60
|
-
const createJsonSchemaTransformObject = ({
|
|
67
|
+
const createJsonSchemaTransformObject = ({ schemaRegistry }) => (input) => {
|
|
61
68
|
if ('swaggerObject' in input) {
|
|
62
69
|
console.warn('This package currently does not support component references for Swagger 2.0');
|
|
63
70
|
return input.swaggerObject;
|
|
64
71
|
}
|
|
65
|
-
|
|
72
|
+
const { schemas } = zod_1.z.toJSONSchema(schemaRegistry, zodtoJSONSchemaOptions);
|
|
73
|
+
return {
|
|
74
|
+
...input.openapiObject,
|
|
75
|
+
components: {
|
|
76
|
+
...input.openapiObject.components,
|
|
77
|
+
schemas: {
|
|
78
|
+
...input.openapiObject.components?.schemas,
|
|
79
|
+
...schemas,
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
};
|
|
66
83
|
};
|
|
67
84
|
exports.createJsonSchemaTransformObject = createJsonSchemaTransformObject;
|
|
68
|
-
|
|
85
|
+
exports.jsonSchemaTransformObject = (0, exports.createJsonSchemaTransformObject)({
|
|
86
|
+
schemaRegistry: zod_1.z.globalRegistry,
|
|
87
|
+
});
|
|
88
|
+
const validatorCompiler = ({ schema }) => (data) => {
|
|
69
89
|
const result = schema.safeParse(data);
|
|
70
90
|
if (result.error) {
|
|
71
|
-
return { error: (0, errors_1.createValidationError)(result.error
|
|
91
|
+
return { error: (0, errors_1.createValidationError)(result.error) };
|
|
72
92
|
}
|
|
73
93
|
return { value: result.data };
|
|
74
94
|
};
|
|
@@ -86,7 +106,7 @@ const createSerializerCompiler = (options) => ({ schema: maybeSchema, method, ur
|
|
|
86
106
|
const schema = resolveSchema(maybeSchema);
|
|
87
107
|
const result = schema.safeParse(data);
|
|
88
108
|
if (result.error) {
|
|
89
|
-
throw new errors_1.ResponseSerializationError(result.error
|
|
109
|
+
throw new errors_1.ResponseSerializationError(method, url, { cause: result.error });
|
|
90
110
|
}
|
|
91
111
|
return JSON.stringify(result.data, options?.replacer);
|
|
92
112
|
};
|
package/dist/src/errors.d.ts
CHANGED
|
@@ -1,18 +1,35 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type {
|
|
1
|
+
import type { FastifyError } from 'fastify';
|
|
2
|
+
import type { z } from 'zod';
|
|
3
3
|
declare const ResponseSerializationError_base: import("@fastify/error").FastifyErrorConstructor<{
|
|
4
4
|
code: string;
|
|
5
5
|
}, [{
|
|
6
|
-
cause: ZodError;
|
|
6
|
+
cause: z.core.$ZodError;
|
|
7
7
|
}]>;
|
|
8
8
|
export declare class ResponseSerializationError extends ResponseSerializationError_base {
|
|
9
|
-
cause: ZodError;
|
|
10
9
|
method: string;
|
|
11
10
|
url: string;
|
|
12
|
-
|
|
11
|
+
cause: z.core.$ZodError;
|
|
12
|
+
constructor(method: string, url: string, options: {
|
|
13
|
+
cause: z.core.$ZodError;
|
|
14
|
+
});
|
|
13
15
|
}
|
|
16
|
+
export declare function isResponseSerializationError(value: unknown): value is ResponseSerializationError;
|
|
14
17
|
export declare const InvalidSchemaError: import("@fastify/error").FastifyErrorConstructor<{
|
|
15
18
|
code: string;
|
|
16
19
|
}, [string]>;
|
|
17
|
-
|
|
20
|
+
declare const ZodFastifySchemaValidationErrorSymbol: unique symbol;
|
|
21
|
+
export type ZodFastifySchemaValidationError = {
|
|
22
|
+
[ZodFastifySchemaValidationErrorSymbol]: true;
|
|
23
|
+
keyword: string;
|
|
24
|
+
instancePath: string;
|
|
25
|
+
schemaPath: string;
|
|
26
|
+
params: {
|
|
27
|
+
issue: z.core.$ZodIssue;
|
|
28
|
+
};
|
|
29
|
+
message: string;
|
|
30
|
+
};
|
|
31
|
+
export declare const hasZodFastifySchemaValidationErrors: (error: unknown) => error is Omit<FastifyError, "validation"> & {
|
|
32
|
+
validation: ZodFastifySchemaValidationError[];
|
|
33
|
+
};
|
|
34
|
+
export declare const createValidationError: (error: z.core.$ZodError) => ZodFastifySchemaValidationError[];
|
|
18
35
|
export {};
|
package/dist/src/errors.js
CHANGED
|
@@ -3,28 +3,41 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.createValidationError = exports.InvalidSchemaError = exports.ResponseSerializationError = void 0;
|
|
6
|
+
exports.createValidationError = exports.hasZodFastifySchemaValidationErrors = exports.InvalidSchemaError = exports.ResponseSerializationError = void 0;
|
|
7
|
+
exports.isResponseSerializationError = isResponseSerializationError;
|
|
7
8
|
const error_1 = __importDefault(require("@fastify/error"));
|
|
8
9
|
class ResponseSerializationError extends (0, error_1.default)('FST_ERR_RESPONSE_SERIALIZATION', "Response doesn't match the schema", 500) {
|
|
9
|
-
constructor(
|
|
10
|
-
super({ cause });
|
|
11
|
-
this.cause = cause;
|
|
10
|
+
constructor(method, url, options) {
|
|
11
|
+
super({ cause: options.cause });
|
|
12
12
|
this.method = method;
|
|
13
13
|
this.url = url;
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
exports.ResponseSerializationError = ResponseSerializationError;
|
|
17
|
+
function isResponseSerializationError(value) {
|
|
18
|
+
return 'method' in value;
|
|
19
|
+
}
|
|
17
20
|
exports.InvalidSchemaError = (0, error_1.default)('FST_ERR_INVALID_SCHEMA', 'Invalid schema passed: %s', 500);
|
|
18
|
-
const
|
|
19
|
-
|
|
21
|
+
const ZodFastifySchemaValidationErrorSymbol = Symbol.for('ZodFastifySchemaValidationError');
|
|
22
|
+
const isZodFastifySchemaValidationError = (error) => typeof error === 'object' &&
|
|
23
|
+
error !== null &&
|
|
24
|
+
ZodFastifySchemaValidationErrorSymbol in error &&
|
|
25
|
+
error[ZodFastifySchemaValidationErrorSymbol] === true;
|
|
26
|
+
const hasZodFastifySchemaValidationErrors = (error) => typeof error === 'object' &&
|
|
27
|
+
error !== null &&
|
|
28
|
+
'validation' in error &&
|
|
29
|
+
Array.isArray(error.validation) &&
|
|
30
|
+
error.validation.length > 0 &&
|
|
31
|
+
isZodFastifySchemaValidationError(error.validation[0]);
|
|
32
|
+
exports.hasZodFastifySchemaValidationErrors = hasZodFastifySchemaValidationErrors;
|
|
33
|
+
const createValidationError = (error) => error.issues.map((issue) => ({
|
|
34
|
+
[ZodFastifySchemaValidationErrorSymbol]: true,
|
|
35
|
+
keyword: issue.code ?? 'custom',
|
|
20
36
|
instancePath: `/${issue.path.join('/')}`,
|
|
21
37
|
schemaPath: `#/${issue.path.join('/')}/${issue.code}`,
|
|
22
38
|
params: {
|
|
23
39
|
issue,
|
|
24
|
-
zodError: error,
|
|
25
|
-
method,
|
|
26
|
-
url,
|
|
27
40
|
},
|
|
28
|
-
message:
|
|
41
|
+
message: issue.message,
|
|
29
42
|
}));
|
|
30
43
|
exports.createValidationError = createValidationError;
|
package/package.json
CHANGED
|
@@ -1,62 +1,61 @@
|
|
|
1
|
-
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
"
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
"
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
"
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
"
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
"
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@bram-dc/fastify-type-provider-zod",
|
|
3
|
+
"version": "5.0.0",
|
|
4
|
+
"description": "Zod Type Provider for Fastify@5",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"README.md",
|
|
9
|
+
"LICENSE",
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsc",
|
|
14
|
+
"test": "npm run build && npm run typescript && vitest",
|
|
15
|
+
"test:coverage": "vitest --coverage",
|
|
16
|
+
"lint": "biome check . && tsc --project tsconfig.lint.json --noEmit",
|
|
17
|
+
"lint:fix": "biome check --write .",
|
|
18
|
+
"typescript": "tsd",
|
|
19
|
+
"prepublishOnly": "npm run build"
|
|
20
|
+
},
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"fastify": "^5.0.0",
|
|
23
|
+
"zod": "^4.0.0-beta.20250412T085909"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"url": "https://github.com/turkerdev/fastify-type-provider-zod"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"fastify",
|
|
30
|
+
"zod",
|
|
31
|
+
"type",
|
|
32
|
+
"provider"
|
|
33
|
+
],
|
|
34
|
+
"author": "turkerd",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"bugs": {
|
|
37
|
+
"url": "https://github.com/turkerdev/fastify-type-provider-zod/issues"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://github.com/turkerdev/fastify-type-provider-zod",
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@fastify/error": "^4.0.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@biomejs/biome": "^1.9.3",
|
|
45
|
+
"@fastify/swagger": "^9.1.0",
|
|
46
|
+
"@fastify/swagger-ui": "^5.0.1",
|
|
47
|
+
"@kibertoad/biome-config": "^1.2.1",
|
|
48
|
+
"@types/node": "^20.16.10",
|
|
49
|
+
"@vitest/coverage-v8": "^2.1.2",
|
|
50
|
+
"fastify": "^5.0.0",
|
|
51
|
+
"fastify-plugin": "^5.0.1",
|
|
52
|
+
"oas-validator": "^5.0.8",
|
|
53
|
+
"tsd": "^0.31.2",
|
|
54
|
+
"typescript": "^5.6.2",
|
|
55
|
+
"vitest": "^2.1.2",
|
|
56
|
+
"zod": "^4.0.0-beta.20250412T085909"
|
|
57
|
+
},
|
|
58
|
+
"tsd": {
|
|
59
|
+
"directory": "types"
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { z, ZodIssue } from 'zod';
|
|
2
|
-
export type ResponseValidationErrorDetails = {
|
|
3
|
-
error: ZodIssue[];
|
|
4
|
-
method: string;
|
|
5
|
-
url: string;
|
|
6
|
-
};
|
|
7
|
-
export declare class ResponseValidationError extends Error {
|
|
8
|
-
details: ResponseValidationErrorDetails;
|
|
9
|
-
constructor(validationResult: z.SafeParseReturnType<unknown, unknown>, method: string, url: string);
|
|
10
|
-
}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.ResponseValidationError = void 0;
|
|
4
|
-
class ResponseValidationError extends Error {
|
|
5
|
-
constructor(validationResult, method, url) {
|
|
6
|
-
super("Response doesn't match the schema");
|
|
7
|
-
this.name = 'ResponseValidationError';
|
|
8
|
-
this.details = {
|
|
9
|
-
error: validationResult.error?.issues ?? [],
|
|
10
|
-
method,
|
|
11
|
-
url,
|
|
12
|
-
};
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
exports.ResponseValidationError = ResponseValidationError;
|
package/dist/src/ref.d.ts
DELETED
package/dist/src/ref.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.resolveRefs = void 0;
|
|
4
|
-
const zod_to_json_1 = require("./zod-to-json");
|
|
5
|
-
const createComponentMap = (schemas) => {
|
|
6
|
-
const map = new Map();
|
|
7
|
-
Object.entries(schemas).forEach(([key, value]) => map.set(JSON.stringify(value), key));
|
|
8
|
-
return map;
|
|
9
|
-
};
|
|
10
|
-
const createComponentReplacer = (componentMapVK, schemasObject) =>
|
|
11
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
12
|
-
function componentReplacer(key, value) {
|
|
13
|
-
if (typeof value !== 'object')
|
|
14
|
-
return value;
|
|
15
|
-
// Check if the parent is the schemas object, if so, return the value as is. This is where the schemas are defined.
|
|
16
|
-
if (this === schemasObject)
|
|
17
|
-
return value;
|
|
18
|
-
const stringifiedValue = JSON.stringify(value);
|
|
19
|
-
if (componentMapVK.has(stringifiedValue))
|
|
20
|
-
return { $ref: `#/components/schemas/${componentMapVK.get(stringifiedValue)}` };
|
|
21
|
-
if (value.nullable === true) {
|
|
22
|
-
const nonNullableValue = { ...value };
|
|
23
|
-
delete nonNullableValue.nullable;
|
|
24
|
-
const stringifiedNonNullableValue = JSON.stringify(nonNullableValue);
|
|
25
|
-
if (componentMapVK.has(stringifiedNonNullableValue))
|
|
26
|
-
return {
|
|
27
|
-
anyOf: [
|
|
28
|
-
{ $ref: `#/components/schemas/${componentMapVK.get(stringifiedNonNullableValue)}` },
|
|
29
|
-
],
|
|
30
|
-
nullable: true,
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
return value;
|
|
34
|
-
};
|
|
35
|
-
const resolveRefs = (openapiObject, zodSchemas) => {
|
|
36
|
-
const schemas = {};
|
|
37
|
-
for (const key in zodSchemas) {
|
|
38
|
-
schemas[key] = (0, zod_to_json_1.convertZodToJsonSchema)(zodSchemas[key]);
|
|
39
|
-
}
|
|
40
|
-
const document = {
|
|
41
|
-
...openapiObject,
|
|
42
|
-
components: {
|
|
43
|
-
...openapiObject.components,
|
|
44
|
-
schemas: {
|
|
45
|
-
...openapiObject.components?.schemas,
|
|
46
|
-
...schemas,
|
|
47
|
-
},
|
|
48
|
-
},
|
|
49
|
-
};
|
|
50
|
-
const componentMapVK = createComponentMap(schemas);
|
|
51
|
-
const componentReplacer = createComponentReplacer(componentMapVK, document.components.schemas);
|
|
52
|
-
// Using the componentReplacer function we deep check if the document has any schemas that are the same as the zod schemas provided
|
|
53
|
-
// When a match is found replace them with a $ref.
|
|
54
|
-
return JSON.parse(JSON.stringify(document, componentReplacer));
|
|
55
|
-
};
|
|
56
|
-
exports.resolveRefs = resolveRefs;
|
package/dist/src/zod-to-json.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.convertZodToJsonSchema = void 0;
|
|
4
|
-
const zod_to_json_schema_1 = require("zod-to-json-schema");
|
|
5
|
-
const zodToJsonSchemaOptions = {
|
|
6
|
-
target: 'openApi3',
|
|
7
|
-
$refStrategy: 'none',
|
|
8
|
-
};
|
|
9
|
-
const convertZodToJsonSchema = (zodSchema) => {
|
|
10
|
-
return (0, zod_to_json_schema_1.zodToJsonSchema)(zodSchema, zodToJsonSchemaOptions);
|
|
11
|
-
};
|
|
12
|
-
exports.convertZodToJsonSchema = convertZodToJsonSchema;
|