@nsilly/support
Version:
NSilly Support package
89 lines (67 loc) • 1.99 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.Transformer = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _exceptions = require("@nsilly/exceptions");
var Transformer =
/*#__PURE__*/
function () {
function Transformer(includes) {
if (includes === void 0) {
includes = [];
}
if (includes.length > 0) {
this.includes = includes;
} else if (_lodash.default.isFunction(this.defaultIncludes)) {
var default_permissions = this.defaultIncludes();
if (_lodash.default.isArray(default_permissions) && default_permissions.length > 0) {
this.includes = default_permissions;
} else {
this.includes = [];
}
} else {
this.includes = [];
}
}
var _proto = Transformer.prototype;
_proto.item = function item(obj, transformer) {
if (_lodash.default.isNil(obj)) {
return null;
}
return {
data: transformer.get(obj)
};
};
_proto.collection = function collection(_collection, transformer) {
if (!_lodash.default.isArray(_collection)) {
return [];
}
var data = _lodash.default.map(_collection, function (i) {
return transformer.get(i);
});
return {
data: data
};
};
_proto.get = function get(model) {
var _this = this;
var data = this.transform(model);
if (this.includes.length > 0) {
_lodash.default.forEach(this.includes, function (include) {
var f = _lodash.default.camelCase("include_" + include);
if (!_lodash.default.isFunction(_this[f])) {
throw new _exceptions.Exception(f + " function is missing", 1000);
}
data[include] = _this[f](model);
});
}
return data;
};
_proto.with = function _with(include) {
this.includes.push(include);
return this;
};
return Transformer;
}();
exports.Transformer = Transformer;