nginx-proxy-manager-zh/backend/lib/validator/index.js
Jamie Curnow dfe2588523
Refactor API Schema and validation
- /schema now returns full openapi/swagger schema
- That schema is used to validate incoming requests
- And used as a contract in future integration tests
- Moved route files up one level
- Fixed incorrect 404 reponses when getting objects
- Fixed saving new objects and passing jsonschemavalidation
2024-10-09 18:05:15 +10:00

45 lines
1.0 KiB
JavaScript

const _ = require('lodash');
const error = require('../error');
const commonDefinitions = require('../../schema/common.json');
RegExp.prototype.toJSON = RegExp.prototype.toString;
const ajv = require('ajv')({
verbose: true,
allErrors: true,
format: 'full', // strict regexes for format checks
coerceTypes: true,
schemas: [commonDefinitions]
});
/**
*
* @param {Object} schema
* @param {Object} payload
* @returns {Promise}
*/
function validator (schema, payload) {
return new Promise(function (resolve, reject) {
if (!payload) {
reject(new error.InternalValidationError('Payload is falsy'));
} else {
try {
let validate = ajv.compile(schema);
let valid = validate(payload);
if (valid && !validate.errors) {
resolve(_.cloneDeep(payload));
} else {
let message = ajv.errorsText(validate.errors);
reject(new error.InternalValidationError(message));
}
} catch (err) {
reject(err);
}
}
});
}
module.exports = validator;