Files

46 lines
1018 B
JavaScript
Raw Permalink Normal View History

2025-09-02 21:43:00 +10:00
import Ajv from 'ajv/dist/2020.js';
import _ from "lodash";
import commonDefinitions from "../../schema/common.json" with { type: "json" };
import errs from "../error.js";
2020-02-19 15:55:06 +11:00
RegExp.prototype.toJSON = RegExp.prototype.toString;
2024-10-10 15:53:11 +10:00
const ajv = new Ajv({
2025-09-02 21:43:00 +10:00
verbose: true,
allErrors: true,
2024-10-10 15:53:11 +10:00
allowUnionTypes: true,
2025-09-02 21:43:00 +10:00
coerceTypes: true,
strict: false,
schemas: [commonDefinitions],
2020-02-19 15:55:06 +11:00
});
/**
*
* @param {Object} schema
* @param {Object} payload
* @returns {Promise}
*/
2025-09-02 21:43:00 +10:00
const validator = (schema, payload) => {
return new Promise((resolve, reject) => {
2020-02-19 15:55:06 +11:00
if (!payload) {
2025-09-02 21:43:00 +10:00
reject(new errs.InternalValidationError("Payload is falsy"));
2020-02-19 15:55:06 +11:00
} else {
try {
2025-09-02 21:43:00 +10:00
const validate = ajv.compile(schema);
const valid = validate(payload);
2020-02-19 15:55:06 +11:00
if (valid && !validate.errors) {
resolve(_.cloneDeep(payload));
} else {
2025-09-02 21:43:00 +10:00
const message = ajv.errorsText(validate.errors);
reject(new errs.InternalValidationError(message));
2020-02-19 15:55:06 +11:00
}
} catch (err) {
reject(err);
}
}
});
2025-09-02 21:43:00 +10:00
};
2020-02-19 15:55:06 +11:00
2025-09-02 21:43:00 +10:00
export default validator;