UNPKG

redux-resource-support-unshift-list

Version:
75 lines (58 loc) 3.08 kB
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; import warning from './warning'; // Add or update resources export default function upsertResources(resources, newResources, mergeResources) { if (!newResources) { return resources; } var mergeResourcesOption = typeof mergeResources !== 'undefined' ? mergeResources : true; var shallowClone = Object.assign({}, resources); if (Array.isArray(newResources)) { newResources.forEach(function (resource) { var resourceIsObject = (typeof resource === 'undefined' ? 'undefined' : _typeof(resource)) === 'object'; var id = resourceIsObject ? resource.id : resource; // If a resource doesn't have an ID, then it cannot be tracked if (!id && id !== 0) { if (process.env.NODE_ENV !== 'production') { warning('You attempted to update or add a resource without an ID attribute. ' + 'Redux Resource requires that all resources have an ID. You should ' + 'double-check your Action Creators to make sure that all entries in ' + 'are either an ID or an object with an "id" attribute. ' + 'For more information, refer to the documentation on resource objects at: ' + 'https://redux-resource.js.org/docs/resources/resource-objects.html', 'MISSING_ID_UPSERT'); } return; } var resourceObj = resourceIsObject ? resource : { id: resource }; var resourceAlreadyExists = Boolean(resources[id]); // If there is no existing resource, we just add it to the resources object if (!resourceAlreadyExists) { shallowClone[id] = resourceObj; return shallowClone; } var resourceToInsert = void 0; if (mergeResourcesOption) { var currentResource = shallowClone[id]; resourceToInsert = Object.assign({}, currentResource, resourceObj); } else { resourceToInsert = resourceObj; } shallowClone[id] = resourceToInsert; }); } else { for (var id in newResources) { var resource = newResources[id]; var resourceAlreadyExists = Boolean(resources[id]); // If there is no existing resource, we just add it to the resources object if (!resourceAlreadyExists) { shallowClone[id] = resource; continue; } var resourceToInsert = void 0; if (mergeResourcesOption) { var currentResource = shallowClone[id]; resourceToInsert = Object.assign({}, currentResource, resource); } else { resourceToInsert = _extends({}, resource); } shallowClone[id] = resourceToInsert; } } return shallowClone; }