UNPKG

typedconverter

Version:

Convert object into classes match with TypeScript type annotation

52 lines (51 loc) 2.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RequiredValidator = exports.createValidator = exports.validate = exports.val = exports.PartialValidator = exports.validatorVisitor = exports.partial = exports.Result = exports.convert = void 0; const decorators_1 = require("./decorators"); Object.defineProperty(exports, "val", { enumerable: true, get: function () { return decorators_1.val; } }); const transformer_1 = require("./transformer"); const validation_1 = require("./validation"); Object.defineProperty(exports, "partial", { enumerable: true, get: function () { return validation_1.partial; } }); Object.defineProperty(exports, "PartialValidator", { enumerable: true, get: function () { return validation_1.PartialValidator; } }); Object.defineProperty(exports, "validatorVisitor", { enumerable: true, get: function () { return validation_1.validatorVisitor; } }); Object.defineProperty(exports, "RequiredValidator", { enumerable: true, get: function () { return validation_1.RequiredValidator; } }); const visitor_1 = require("./visitor"); Object.defineProperty(exports, "Result", { enumerable: true, get: function () { return visitor_1.Result; } }); /** * Convert value into type specified on configuration. * @param value * @param opt */ function convert(value, option) { const opt = "type" in option ? option : { type: option }; return visitor_1.pipeline(value, transformer_1.transform(opt.type), { path: opt.path || "", extension: opt.visitors || [], decorators: opt.decorators || [], guessArrayElement: opt.guessArrayElement || false }); } exports.convert = convert; /** * Create type converter with specific configuration * @param option */ function createConverter(option) { return (value) => convert(value, option); } exports.default = createConverter; function createValidator(option) { return (value) => validate(value, option); } exports.createValidator = createValidator; function validate(value, option) { const opt = "type" in option ? option : { type: option }; const visitors = [validation_1.validatorVisitor]; for (const visitor of (opt.visitors || [])) { visitors.push(visitor); } return convert(value, { decorators: opt.decorators, guessArrayElement: opt.guessArrayElement, path: opt.path, type: opt.type, visitors }); } exports.validate = validate;