@apizr-io/class-utils
Version:
Package containing all class-validator function with all custom apizr class validation functions
47 lines • 2.47 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConditionalKeyValidator = exports.ValidateSubKeyExistIf = void 0;
const class_validator_1 = require("class-validator");
const jsonpath_plus_1 = require("jsonpath-plus");
const class_decorator_1 = require("./class.decorator");
/**
* Allows validating the presence of a specified key in a child object based on a given condition
*/
function ValidateSubKeyExistIf(path, condition) {
return (0, class_decorator_1.registerClassValidator)({
name: 'validateSubKeyExistIf',
constraints: [condition, path],
validator: ConditionalKeyValidator,
});
}
exports.ValidateSubKeyExistIf = ValidateSubKeyExistIf;
let ConditionalKeyValidator = exports.ConditionalKeyValidator = class ConditionalKeyValidator {
// validate the presence of a key in a child object based on a given condition
validate(value, args) {
const [condition, path] = args.constraints;
const object = args.object;
// if the condition is not met, then the validation passes
if (!condition(object)) {
return true;
}
// create a jsonpath query to get the value of the path
const values = (0, jsonpath_plus_1.JSONPath)({ path: `$.${path}`, json: object });
return (values.length !== 0 &&
values.every((value) => value !== undefined && value !== null && value !== ''));
}
defaultMessage(args) {
// error message if validation failed
const [condition, path] = args.constraints;
return `One of the following keys ${path} must be defined if ${condition} is true`;
}
};
exports.ConditionalKeyValidator = ConditionalKeyValidator = __decorate([
(0, class_validator_1.ValidatorConstraint)({ name: 'conditionalKey', async: false })
], ConditionalKeyValidator);
//# sourceMappingURL=validate.decorator.js.map