-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzodValidateOnClient.ts
34 lines (27 loc) · 1.23 KB
/
zodValidateOnClient.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
import type { VovkClientOptions } from 'vovk/client';
import Ajv from 'ajv';
import { HttpException, HttpStatus } from 'vovk';
import addFormats from 'ajv-formats';
const ajv = new Ajv();
addFormats(ajv);
const zodValidateOnClient: VovkClientOptions['validateOnClient'] = (input, validators) => {
if (validators.body) {
const isValid = ajv.validate(validators.body, input.body);
if (!isValid) {
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
console.error('[zodValidateOnClient in dev env] The error below is caused by an invalid body', input.body);
}
throw new HttpException(HttpStatus.NULL, `Invalid request body on client for ${input.endpoint}. ${ajv.errorsText()}`);
}
}
if (validators.query) {
const isValid = ajv.validate(validators.query, input.query);
if (!isValid) {
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
console.error('[zodValidateOnClient in dev env] The error below is caused by an invalid query', input.query);
}
throw new HttpException(HttpStatus.NULL, `Invalid request query on client for ${input.endpoint}. ${ajv.errorsText()}`);
}
}
};
export default zodValidateOnClient;