-
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathajv.ts
More file actions
264 lines (254 loc) · 9.55 KB
/
Copy pathajv.ts
File metadata and controls
264 lines (254 loc) · 9.55 KB
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
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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import Ajv from 'ajv';
import type { ErrorObject } from 'ajv';
import addFormats from 'ajv-formats';
import jsonSerializerFactory from '@ardatan/fast-json-stringify';
import { URL } from '@whatwg-node/fetch';
import { Response } from '../Response.js';
import type { StatusCode } from '../typed-fetch.js';
import type {
JSONSerializer,
PromiseOrValue,
RouterComponentsBase,
RouterPlugin,
RouterRequest,
} from '../types.js';
import { isZodSchema } from '../zod/types.js';
import { getHeadersObj } from './utils.js';
type ValidateRequestFn = (request: RouterRequest) => PromiseOrValue<ErrorObject[]>;
export function useAjv({
components = { schemas: {} },
}: {
components?: RouterComponentsBase | undefined;
} = {}): RouterPlugin<any> {
const ajv = new Ajv({
strict: false,
strictSchema: false,
validateSchema: false,
allowUnionTypes: true,
uriResolver: {
parse(uri: string) {
const url = new URL(uri);
return {
scheme: url.protocol,
userinfo: url.username + (url.password ? ':' + url.password : ''),
host: url.hostname,
port: url.port,
path: url.pathname,
query: url.search,
fragment: url.hash,
};
},
resolve(base: string, ref: string) {
return new URL(ref, base).toString();
},
serialize(components) {
return (
components.scheme +
'://' +
components.userinfo +
components.host +
components.port +
components.path +
components.query +
components.fragment
);
},
},
});
addFormats(ajv);
// Required for fast-json-stringify
ajv.addKeyword({
keyword: 'fjs_type',
type: 'object',
errors: false,
validate: (_type: unknown, date: unknown) => {
return date instanceof Date;
},
});
const serializersByPath = new Map<string, Map<number, JSONSerializer>>();
return {
onRoute({ path, schemas, handlers }) {
const validationMiddlewares = new Map<string, ValidateRequestFn>();
if (schemas?.request?.headers && !isZodSchema(schemas.request.headers)) {
const { headers } = schemas.request;
// TODO: Property '$async' is missing in type '{ components: RouterComponentsBase; type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined; pattern?: string | undefined; ... 46 more ...; [$JSONSchema7]?: unique symbol; }' but required in type 'AsyncSchema'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const validateFn = ajv.compile({
...headers,
components,
});
validationMiddlewares.set('headers', request => {
const headersObj = getHeadersObj(request.headers);
const isValid = validateFn(headersObj);
if (!isValid) {
return validateFn.errors!;
}
return [];
});
}
if (schemas?.request?.params && !isZodSchema(schemas.request.params)) {
// TODO: Property '$async' is missing in type '{ components: RouterComponentsBase; type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined; pattern?: string | undefined; ... 46 more ...; [$JSONSchema7]?: unique symbol; }' but required in type 'AsyncSchema'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const validateFn = ajv.compile({
...schemas.request.params,
components,
});
validationMiddlewares.set('params', request => {
const isValid = validateFn(request.params);
if (!isValid) {
return validateFn.errors!;
}
return [];
});
}
if (schemas?.request?.query && !isZodSchema(schemas.request.query)) {
// TODO: Property '$async' is missing in type '{ components: RouterComponentsBase; type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined; pattern?: string | undefined; ... 46 more ...; [$JSONSchema7]?: unique symbol; }' but required in type 'AsyncSchema'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const validateFn = ajv.compile({
...schemas.request.query,
components,
});
validationMiddlewares.set('query', request => {
const isValid = validateFn(request.query);
if (!isValid) {
return validateFn.errors!;
}
return [];
});
}
if (schemas?.request?.json && !isZodSchema(schemas.request.json)) {
// TODO: Property '$async' is missing in type '{ components: RouterComponentsBase; type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined; pattern?: string | undefined; ... 46 more ...; [$JSONSchema7]?: unique symbol; }' but required in type 'AsyncSchema'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const validateFn = ajv.compile({
...schemas.request.json,
components,
});
validationMiddlewares.set('json', async request => {
const contentType = request.headers.get('content-type');
if (contentType?.includes('json')) {
const jsonObj = await request.json();
Object.defineProperty(request, 'json', {
value: async () => jsonObj,
configurable: true,
});
const isValid = validateFn(jsonObj);
if (!isValid) {
return validateFn.errors!;
}
}
return [];
});
}
if (schemas?.request?.formData && !isZodSchema(schemas.request.formData)) {
// TODO: Property '$async' is missing in type '{ components: RouterComponentsBase; type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined; pattern?: string | undefined; ... 46 more ...; [$JSONSchema7]?: unique symbol; }' but required in type 'AsyncSchema'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const validateFn = ajv.compile({
...schemas.request.formData,
components,
});
validationMiddlewares.set('formData', async request => {
const contentType = request.headers.get('content-type');
if (
contentType?.includes('multipart/form-data') ||
contentType?.includes('application/x-www-form-urlencoded')
) {
const formData = await request.formData();
const formDataObj: Record<string, FormDataEntryValue | undefined> = {};
const jobs: Promise<void>[] = [];
formData.forEach((value, key) => {
if (typeof value === 'undefined') {
return;
}
if (typeof value === 'string') {
formDataObj[key] = value;
} else {
jobs.push(
value.arrayBuffer().then((buffer: ArrayBuffer): void => {
const typedArray = new Uint8Array(buffer);
const binaryStrParts: string[] = [];
typedArray.forEach((byte, index) => {
binaryStrParts[index] = String.fromCharCode(byte);
});
formDataObj[key] = binaryStrParts.join('');
}),
);
}
});
await Promise.all(jobs);
Object.defineProperty(request, 'formData', {
value: async () => formData,
configurable: true,
});
const isValid = validateFn(formDataObj);
if (!isValid) {
return validateFn.errors!;
}
}
return [];
});
}
if (jsonSerializerFactory && schemas?.responses) {
const serializerByStatusCode = new Map<number, JSONSerializer>();
for (const statusCode in schemas.responses) {
const schema = schemas.responses[statusCode as unknown as StatusCode];
if (!isZodSchema(schema)) {
const serializer = jsonSerializerFactory(
{
...schema,
components,
} as any,
{
ajv,
},
);
serializerByStatusCode.set(Number(statusCode), serializer);
}
}
serializersByPath.set(path, serializerByStatusCode);
}
if (validationMiddlewares.size > 0) {
handlers.unshift(async (request): Promise<any> => {
const validationErrorsNonFlat = await Promise.all(
[...validationMiddlewares.entries()].map(async ([name, fn]) => {
const errors = await fn(request);
if (errors.length > 0) {
return errors.map(error => ({
name,
...error,
}));
}
}),
);
const validationErrors = validationErrorsNonFlat.flat().filter(Boolean) as ErrorObject[];
if (validationErrors.length > 0) {
return Response.json(
{
errors: validationErrors,
},
{
status: 400,
headers: {
'x-error-type': 'validation',
},
},
);
}
});
}
},
onSerializeResponse({ path, lazyResponse }) {
const serializers = serializersByPath.get(path);
if (serializers) {
const serializer = serializers.get(lazyResponse.init?.status || 200);
if (serializer) {
lazyResponse.resolveWithSerializer(serializer);
}
}
},
};
}