UNPKG

ngx-resource-gearheart

Version:

Angular2 resource module with simple decorators. Customized by Gearheart.

53 lines (52 loc) 2.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function ForeignKey(params) { params.resourceGetAction = !!params.resourceGetAction ? params.resourceGetAction : 'get'; return function (target, propertyKey) { function getForeignFromStorage(id, storage) { var foreignModel = storage.resultData.find(function (item) { return item[item.$primaryKey] === id; }); if (!!foreignModel) { return foreignModel; } } function getForeignFromResource(id, resource) { var action = resource[params.resourceGetAction]; if (!!action) { var queryParams = {}; queryParams[(new params.target()).$primaryKey] = id; return action.bind(resource)(queryParams); } ; } Object.defineProperty(target, propertyKey, { get: function () { var foreignId = this[params.keyField]; var foreignModel; if (foreignId) { // check cached if (this.$cachedRelated[propertyKey] && this.$cachedRelated[propertyKey].id === foreignId) { return this.$cachedRelated[propertyKey].data; } // try to get from storage or from resource var foreignResource = Reflect.getMetadata('resource', params.target); if (!!foreignResource && !!foreignResource.storage) { foreignModel = getForeignFromStorage(foreignId, foreignResource.storage); if (!foreignModel) { foreignModel = getForeignFromResource(foreignId, foreignResource); } } else if (!!foreignResource) { foreignModel = getForeignFromResource(foreignId, foreignResource); } ; //cache it and return if (!!foreignModel) { this.$cachedRelated[propertyKey] = { id: foreignId, data: foreignModel }; return foreignModel; } } } }); }; } exports.ForeignKey = ForeignKey;