-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
54 lines (46 loc) · 1.78 KB
/
index.ts
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
import { HttpException, HttpStatus, createDecorator } from 'vovk';
import { z } from 'zod';
import { default as zodToJsonSchema } from 'zod-to-json-schema';
export { default as zodValidateOnClient } from './zodValidateOnClient';
type KnownAny = any; // eslint-disable-line @typescript-eslint/no-explicit-any
type ZodAny = z.ZodObject<KnownAny> | z.ZodRecord<KnownAny> | z.ZodUnion<KnownAny>;
const vovkZod = createDecorator(
async (req, next, bodyModel?: ZodAny | null, queryModel?: ZodAny | null) => {
if (bodyModel) {
const body = await req.json();
try {
bodyModel.parse(body);
} catch (e) {
const err = (e as z.ZodError).errors.map((er) => `${er.message} (${er.path.join('/')})`).join(', ');
throw new HttpException(HttpStatus.BAD_REQUEST, `Invalid body on server. ${err}`);
}
req.json = () => Promise.resolve(body);
}
if (queryModel) {
const query = Object.fromEntries(req.nextUrl.searchParams.entries());
delete query.nxtP;
try {
queryModel.parse(query);
} catch (e) {
const err = (e as z.ZodError).errors.map((er) => `${er.message} (${er.path.join('/')})`).join(', ');
throw new HttpException(HttpStatus.BAD_REQUEST, `Invalid query on server. ${err}`);
}
}
return next();
},
(bodyModel?: ZodAny | null, queryModel?: ZodAny | null) => {
return (handlerMetadata) => ({
...handlerMetadata,
customMetadata: {
...handlerMetadata?.customMetadata,
[Symbol.for('zodBodyModel')]: bodyModel,
[Symbol.for('zodQueryModel')]: queryModel,
},
clientValidators: {
body: bodyModel ? zodToJsonSchema(bodyModel) : null,
query: queryModel ? zodToJsonSchema(queryModel) : null,
},
});
}
);
export default vovkZod;