Validate json settings with ajv

This commit is contained in:
Shin'ya Ueoka 2019-12-03 14:29:36 +09:00
parent d8556a9b1e
commit 3e2ebb7797
5 changed files with 112 additions and 108 deletions

View file

@ -0,0 +1,20 @@
import Ajv from 'ajv';
export default class Validator<T> {
constructor(
private schema: object | boolean,
) {
}
validate(data: any): T {
let ajv = new Ajv();
let valid = ajv.validate(this.schema, data);
if (!valid) {
let message = ajv.errors!!
.map(err => `'${err.dataPath}' of ${err.keyword} ${err.message}`)
.join('; ');
throw new TypeError(message);
}
return data as T;
}
}