2024-10-09 04:05:15 -04:00
|
|
|
const error = require('../error');
|
2020-02-18 23:55:06 -05:00
|
|
|
|
|
|
|
const ajv = require('ajv')({
|
|
|
|
verbose: true,
|
|
|
|
validateSchema: true,
|
|
|
|
allErrors: false,
|
|
|
|
format: 'full',
|
|
|
|
coerceTypes: true
|
|
|
|
});
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {Object} schema
|
|
|
|
* @param {Object} payload
|
|
|
|
* @returns {Promise}
|
|
|
|
*/
|
|
|
|
function apiValidator (schema, payload/*, description*/) {
|
|
|
|
return new Promise(function Promise_apiValidator (resolve, reject) {
|
2024-10-09 04:05:15 -04:00
|
|
|
if (schema === null) {
|
|
|
|
reject(new error.ValidationError('Schema is undefined'));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-02-18 23:55:06 -05:00
|
|
|
if (typeof payload === 'undefined') {
|
|
|
|
reject(new error.ValidationError('Payload is undefined'));
|
2024-10-09 04:05:15 -04:00
|
|
|
return;
|
2020-02-18 23:55:06 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
let validate = ajv.compile(schema);
|
|
|
|
let valid = validate(payload);
|
|
|
|
|
|
|
|
if (valid && !validate.errors) {
|
|
|
|
resolve(payload);
|
|
|
|
} else {
|
|
|
|
let message = ajv.errorsText(validate.errors);
|
|
|
|
let err = new error.ValidationError(message);
|
|
|
|
err.debug = [validate.errors, payload];
|
|
|
|
reject(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = apiValidator;
|