typedsv
Version:
Parse and map delimiter-separated values (csv, tsv, etc.) to TypeScript/ES6+ classes.
110 lines • 4.27 kB
JavaScript
;
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
var PropertyTypeError_1 = require("../error/PropertyTypeError");
var ValidationError_1 = require("../error/ValidationError");
var Validation_1 = require("./Validation");
var booleanValues = Object.freeze({
true: ['TRUE', 'Y', 'YES', 'T', '1'],
false: ['FALSE', 'N', 'NO', 'F', '0']
});
var ParsedProperty = /** @class */ (function () {
function ParsedProperty(name, options) {
var _this = this;
this.set = function (target, value) {
var _a = _this.options, map = _a.map, validate = _a.validate;
if (map && typeof value === 'string') {
value = map(value);
}
var ok = true;
if (!_this.type) {
_this.type = Reflect.getMetadata('design:type', target, _this.name);
}
if (!(value instanceof _this.type || value.constructor === _this.type)) {
if (typeof value === 'string') {
if (_this.type === Number) {
var num = parseFloat(value.replace(',', ''));
if (!isNaN(num)) {
value = num;
}
else {
ok = false;
}
}
else if (_this.type === Boolean) {
if (booleanValues.true.includes(value.toUpperCase())) {
value = true;
}
else if (booleanValues.false.includes(value.toUpperCase())) {
value = false;
}
else {
ok = false;
}
}
}
else {
ok = false;
}
}
if (validate) {
_this.validate(value, validate);
}
if (!ok || !Reflect.set(target, _this.name, value)) {
throw new PropertyTypeError_1.PropertyTypeError(target, _this, value);
}
};
this.validate = function (value, options) {
var aggregate = options.aggregate, functions = options.functions;
var errors = [];
functions.forEach(function (v, index) {
var f;
var message;
if (Validation_1.isValidateObject(v)) {
f = v.function;
message = v.message;
}
else {
f = v;
}
if (!message) {
message = "validate." + index;
}
var result = f(value);
if (!result) {
if (aggregate) {
errors.push(message);
}
else {
throw new ValidationError_1.ValidationError(_this, value, message);
}
}
});
if (errors.length > 0) {
throw new (ValidationError_1.ValidationError.bind.apply(ValidationError_1.ValidationError, __spreadArrays([void 0, _this, value], errors)))();
}
};
this.name = name;
this.options = options || {};
var validate = this.options.validate;
if (validate) {
if (validate instanceof Array) {
validate = { functions: validate };
}
else if (Validation_1.isValidateType(validate)) {
validate = { functions: [validate] };
}
this.options.validate = validate;
}
}
return ParsedProperty;
}());
exports.ParsedProperty = ParsedProperty;
//# sourceMappingURL=ParsedProperty.js.map