UNPKG

@intuitionrobotics/ts-common

Version:
174 lines 7.75 kB
"use strict"; /* * ts-common is the basic building blocks of our typescript projects * * Copyright (C) 2020 Intuition Robotics * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.validateEmail = exports.timestampValidator = exports.auditValidator = exports.isTimestampValid = exports.validateObject = exports.validate = exports.validateRange = exports.validateValue = exports.validateRegexp = exports.validateArray = exports.validateObjectValues = exports.validateBoolean = exports.validateNumber = exports.validateString = exports.validateType = exports.validateExists = exports.ValidationException = void 0; const exceptions_1 = require("../core/exceptions"); const tools_1 = require("../utils/tools"); const object_tools_1 = require("../utils/object-tools"); const __1 = require(".."); class ValidationException extends exceptions_1.CustomException { constructor(debugMessage, path, input) { super(ValidationException, debugMessage); this.path = path; this.input = input; } } exports.ValidationException = ValidationException; const assertMandatory = (mandatory, path, input) => { if (input !== undefined && input !== null) return; if (mandatory) throw new ValidationException(`Missing mandatory field: ${path}\n`, path, input); }; const validateExists = (mandatory = true) => { return (path, input) => { assertMandatory(mandatory, path, input); }; }; exports.validateExists = validateExists; const validateType = (type, mandatory = true) => { return (path, input) => { assertMandatory(mandatory, path, input); const typeOfInput = typeof input; if (input && typeOfInput !== type) throw new ValidationException(`Got ${typeOfInput} when expecting ${type} for field: ${path}\n`, path, input); }; }; exports.validateType = validateType; const validateString = (mandatory = true) => { return (0, exports.validateType)('string', mandatory); }; exports.validateString = validateString; const validateNumber = (mandatory = true) => { return (0, exports.validateType)('number', mandatory); }; exports.validateNumber = validateNumber; const validateBoolean = (mandatory = true) => { return (0, exports.validateType)('boolean', mandatory); }; exports.validateBoolean = validateBoolean; const validateObjectValues = (validator, mandatory = true) => (path, input) => { assertMandatory(mandatory, path, input); if (!input) return; for (const key of (0, object_tools_1._keys)(input)) { const inputValue = input[key]; if (typeof inputValue === "object") { const objectValidator = (0, exports.validateObjectValues)(validator, mandatory); if (!objectValidator) return; return objectValidator(`${path}/${key}`, inputValue); } (0, exports.validate)(inputValue, validator, `${path}/${key}`); } }; exports.validateObjectValues = validateObjectValues; const validateArray = (validator, mandatory = true) => (path, input) => { assertMandatory(mandatory, path, input); if (!input) return; const _input = input; for (let i = 0; i < _input.length; i++) { (0, exports.validate)(_input[i], validator, `${path}/${i}`); } }; exports.validateArray = validateArray; const validateRegexp = (regexp, mandatory = true) => { return (path, input) => { assertMandatory(mandatory, path, input); if (!input) return; if (regexp.test(input)) return; throw new ValidationException(`Input is not valid:\n input: ${input}\n regexp: ${regexp}\n`, path, input); }; }; exports.validateRegexp = validateRegexp; const validateValue = (values, mandatory = true) => { return (path, input) => { assertMandatory(mandatory, path, input); if (!input) return; if (values.includes(input)) return; throw new ValidationException(`Input is not valid:\n input: ${input}\n options: ${(0, tools_1.__stringify)(values)}\n`, path, input); }; }; exports.validateValue = validateValue; const validateRange = (ranges, mandatory = true) => { return (path, input) => { assertMandatory(mandatory, path, input); if (!input) return; for (const range of ranges) { if (range[0] <= input && input <= range[1]) return; } throw new ValidationException(`Input is not valid:\n input: ${input}\n regexp: ${(0, tools_1.__stringify)(ranges)}\n`, path, input); }; }; exports.validateRange = validateRange; const validate = (instance, _validator, path = "") => { if (!_validator) return; if (typeof _validator === "function") { const validator = _validator; if (!validator) return; return validator(`${path}`, instance); } if (typeof _validator === "object") { if (!instance && _validator) throw new exceptions_1.BadImplementationException(`Unexpect object at '${path}'\nif you want to ignore the validation of this object,\n add the following to your validator:\n {\n ...\n ${path}: undefined\n ...\n}\n`); const __validator = _validator; (0, exports.validateObject)(__validator, instance, path); } }; exports.validate = validate; const validateObject = (__validator, instance, path = "") => { const validatorKeys = (0, object_tools_1._keys)(__validator); const instanceKeys = Object.keys(instance); for (const key of instanceKeys) { // @ts-ignore if (!validatorKeys.includes(key)) throw new exceptions_1.BadImplementationException(`Unexpect key '${path}${key}'\nif you want to ignore the validation of this property,\n add the following to your validator:\n {\n ...\n ${key}: undefined\n ...\n}\nAvailable keys are ${validatorKeys.join()}`); } for (const key of validatorKeys) { const value = instance[key]; const validator = __validator[key]; (0, exports.validate)(value, validator, `${path}/${key}`); } }; exports.validateObject = validateObject; const isTimestampValid = (time, range = { min: (0, __1.currentTimeMillies)() - 1000 * __1.Day, max: (0, __1.currentTimeMillies)() + 1000 * __1.Day }) => { return time >= range.min && time <= range.max; }; exports.isTimestampValid = isTimestampValid; const auditValidator = (range) => (_path, audit) => { var _a; (0, exports.timestampValidator)(range)(_path, (_a = audit === null || audit === void 0 ? void 0 : audit.auditAt) === null || _a === void 0 ? void 0 : _a.timestamp); }; exports.auditValidator = auditValidator; const timestampValidator = (range) => (_path, timestamp) => { if (!timestamp || !(0, exports.isTimestampValid)(timestamp, range)) throw new ValidationException('Time is not proper', _path, timestamp); }; exports.timestampValidator = timestampValidator; exports.validateEmail = (0, exports.validateRegexp)(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/); //# sourceMappingURL=validator.js.map