Files
nginx-proxy-manager/backend/lib/validator/api.js
T

44 lines
964 B
JavaScript
Raw 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}
*/
2025-09-02 21:43:00 +10:00
function apiValidator(schema, payload /*, description*/) {
return new Promise(function Promise_apiValidator(resolve, reject) {
2024-10-09 18:05:15 +10:00
if (schema === null) {
2025-09-02 21:43:00 +10:00
reject(new errs.ValidationError("Schema is undefined"));
2024-10-09 18:05:15 +10:00
return;
}
2025-09-02 21:43:00 +10:00
if (typeof payload === "undefined") {
reject(new errs.ValidationError("Payload is undefined"));
2024-10-09 18:05:15 +10:00
return;
2020-02-19 15:55:06 +11:00
}
2024-10-10 15:53:11 +10:00
const validate = ajv.compile(schema);
2025-09-02 21:43:00 +10:00
const valid = validate(payload);
2020-02-19 15:55:06 +11:00
if (valid && !validate.errors) {
resolve(payload);
} else {
2025-09-02 21:43:00 +10:00
const message = ajv.errorsText(validate.errors);
const err = new errs.ValidationError(message);
err.debug = [validate.errors, payload];
2020-02-19 15:55:06 +11:00
reject(err);
}
});
}
2025-09-02 21:43:00 +10:00
export default apiValidator;