UNPKG

fluorine-orchestra

Version:
118 lines (93 loc) 2.99 kB
import _Object$keys from 'babel-runtime/core-js/object/keys'; import invariant from 'invariant'; import { Store } from '../Store'; import toMap from './toMap'; import { Iterable, Map, Set } from 'immutable'; import { STORE_INSERT, STORE_REMOVE, STORE_FILTER, STORE_UPDATE } from '../constants/StoreConstants'; export default function createReducerForStore(store) { invariant(store && Store.isStore(store), 'Reducer: `store` is expected to be an Orchestra.Store.'); var identifier = store.getIdentifier(); var pre = store.getPre(); var initial = store.createCollection(); return function storeReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initial; var action = arguments[1]; if (identifier !== action.identifier) { return state; } var type = action.type; var payload = action.payload; var groupId = action.groupId; var selector = action.selector; function _ref(x) { var item = pre(selector(x)); return item ? item : x; } switch (type) { case STORE_INSERT: { var _ret = function () { if (Map.isMap(payload)) { var item = pre(payload); if (!item) { return { v: state }; } var id = item.get('id'); var _res = state.set(id, item); return { v: groupId ? _res.addIdToGroup(groupId, id) : _res }; } // Deduping the incoming data by ids, since Immutable has a bug where keys // have to be unique while using mutable data. var track = {}; var res = state.asMutable(); payload.forEach(function (value) { var item = pre(value); if (!item) { return state; } var id = item.get('id'); if (!track[id]) { track[id] = true; res.set(id, item); } }); res = res.asImmutable(); return { v: groupId ? res.addIdsToGroup(groupId, new Set(_Object$keys(track))) : res }; }(); if (typeof _ret === "object") return _ret.v; } case STORE_REMOVE: { if (!payload) { return state; } else if (Map.isMap(payload)) { var id = payload.get('id'); return state.delete(id); } return state.delete(payload); } case STORE_FILTER: { if (typeof selector !== 'function') { return state; } return state.filter(selector); } case STORE_UPDATE: { if (typeof selector !== 'function') { return state; } return state.map(_ref); } default: return state; } }; }