Files

46 lines
928 B
JavaScript
Raw Permalink Normal View History

2025-09-02 21:43:00 +10:00
import Ajv from "ajv/dist/2020.js";
import errs from "../error.js";
2020-02-19 15:55:06 +11:00
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
strict: false,
coerceTypes: true,
2020-02-19 15:55:06 +11:00
});
/**
* @param {Object} schema
* @param {Object} payload
* @returns {Promise}
*/
const apiValidator = async (schema, payload /*, description*/) => {
if (!schema) {
throw new errs.ValidationError("Schema is undefined");
}
2024-10-09 18:05:15 +10:00
// Can't use falsy check here as valid payload could be `0` or `false`
if (typeof payload === "undefined") {
throw new errs.ValidationError("Payload is undefined");
}
2020-02-19 15:55:06 +11:00
2025-10-26 00:28:03 +10:00
const validate = ajv.compile(schema);
2025-10-26 00:28:03 +10:00
const valid = validate(payload);
2020-02-19 15:55:06 +11:00
2025-10-26 00:28:03 +10:00
if (valid && !validate.errors) {
return payload;
}
2025-10-26 00:28:03 +10:00
const message = ajv.errorsText(validate.errors);
const err = new errs.ValidationError(message);
2025-10-26 00:28:03 +10:00
err.debug = {validationErrors: validate.errors, payload};
throw err;
};
2020-02-19 15:55:06 +11:00
2025-09-02 21:43:00 +10:00
export default apiValidator;