parse-js
Version:
Utility library for object structure conversion.
53 lines (39 loc) • 1.59 kB
JavaScript
;
var _isPlainObject = require('lodash/isPlainObject');
var _transform = require('../lib/transform');
var _merge = require('lodash/merge');
function SpecTransformer(spec, parse) {
if (!(this instanceof SpecTransformer)) {
return this.transform(new SpecTransformer(spec, this.constructor));
}
this._parse = parse || require('../index');
this._spec = this._completeSpec(spec);
}
SpecTransformer.prototype._completeSpec = function (spec) {
var _this = this;
var parse = this._parse;
return _transform(spec, function (r, v, k) {
if (typeof v === 'string') v = parse(v);else if (_isPlainObject(v)) v = _this._completeSpec(v);
r[k] = v;
}, {});
};
SpecTransformer.prototype.parse = function (source, instance, root) {
return this._toSpec(this._spec, source, instance, root);
};
SpecTransformer.prototype._toSpec = function (spec, data, instance, root) {
var _this2 = this;
return _transform(spec, function (r, v, k) {
if (_isPlainObject(v)) r[k] = _this2._toSpec(v, data, instance, root);else r[k] = v.parse(data, instance, root);
}, {});
};
SpecTransformer.prototype.reverse = function (source, instance, root) {
return this._fromSpec(this._spec, source, instance, root);
};
SpecTransformer.prototype._fromSpec = function (spec, data, instance, root) {
var _this3 = this;
return _transform(spec, function (r, v, k) {
var value = data && data[k];
if (_isPlainObject(v)) _merge(r, _this3._fromSpec(v, value, instance, root));else _merge(r, v.reverse(value, instance, root));
}, {});
};
module.exports = SpecTransformer;