Validate json settings with ajv
This commit is contained in:
parent
d8556a9b1e
commit
3e2ebb7797
5 changed files with 112 additions and 108 deletions
20
src/shared/settings/Validator.ts
Normal file
20
src/shared/settings/Validator.ts
Normal 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;
|
||||
}
|
||||
}
|
Reference in a new issue