forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhar-validator.ts
More file actions
31 lines (28 loc) · 784 Bytes
/
har-validator.ts
File metadata and controls
31 lines (28 loc) · 784 Bytes
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
import Ajv, { ErrorObject } from 'ajv';
import { Request } from 'har-format';
import * as schema from 'har-schema';
export class HARError extends Error {
name = 'HARError';
message = 'validation failed';
errors: ErrorObject[] = [];
constructor(errors: ErrorObject[]) {
super();
this.errors = errors;
Error.captureStackTrace(this, this.constructor);
}
}
const ajv = new Ajv({
allErrors: true,
});
ajv.addSchema(schema);
export const validateHarRequest = (request: any): request is Request => {
const validate = ajv.getSchema('request.json');
if (!validate) {
throw new Error('failed to find HAR request schema');
}
const valid = validate(request);
if (!valid && validate.errors) {
throw new HARError(validate.errors);
}
return true;
};