UNPKG

ts-deserializable

Version:

Decorator pattern for deserializing unverified data to an instance of a class in typescript.

140 lines (139 loc) 3.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ds_attributes_1 = require("./ds-attributes"); const ds_operations_1 = require("./ds-operations"); var DsOperationType; (function (DsOperationType) { DsOperationType["Operator"] = "OPERATOR"; DsOperationType["Resolver"] = "RESOLVER"; DsOperationType["Validator"] = "VALIDATOR"; })(DsOperationType = exports.DsOperationType || (exports.DsOperationType = {})); const getNestedPropValue = (obj, propPath, separator = '.') => { let pathList = Array.isArray(propPath) ? propPath : propPath.split(separator); return pathList.reduce((prev, curr) => prev && prev[curr], obj); }; class DsPropBuilder { constructor() { this.operations = []; } addOperation(operation) { this.operations = [...this.operations, operation]; } // Basic Operators /** * * @param func */ tap(func) { this.addOperation({ func: (obj) => { func(); return obj; }, type: DsOperationType.Operator }); return this; } /** * * @param func */ map(func) { this.addOperation({ func: func, type: DsOperationType.Operator }); return this; } /** * * @param ctor */ mapTo(ctor) { this.addOperation({ func: (obj) => new ctor().deserialize(obj), type: DsOperationType.Operator }); return this; } /** * * @param ctor */ mapToArray(ctor) { this.addOperation({ func: (obj) => obj.map(child => new ctor().deserialize(child)), type: DsOperationType.Operator }); return this; } // Resolvers /** * * @param func */ resolve(func) { this.addOperation({ func: func, type: DsOperationType.Resolver }); return this; } /** * * @param propPath */ dotResolve(propPath) { this.addOperation({ func: (obj) => getNestedPropValue(obj, propPath), type: DsOperationType.Resolver }); return this; } // Validators validate(func) { this.addOperation({ func: func, type: DsOperationType.Validator }); return this; } validateString() { this.addOperation({ func: (val) => (typeof val === 'string'), type: DsOperationType.Validator }); return this; } validateNumber() { this.addOperation({ func: (val) => (typeof val === 'number'), type: DsOperationType.Validator }); return this; } validateBoolean() { this.addOperation({ func: (val) => (typeof val === 'boolean'), type: DsOperationType.Validator }); return this; } validateArray() { this.addOperation({ func: (val) => Array.isArray(val), type: DsOperationType.Validator }); return this; } // Build /** * * @param fallbackValue */ fb(fallbackValue = undefined) { return (target, key) => { const type = Reflect.getMetadata("design:type", target, key); ds_operations_1.DsOperations.add(target, key, this.operations); ds_attributes_1.DsAttributes.add(target, key, type, fallbackValue); }; } } exports.DsProp = () => new DsPropBuilder();