UNPKG

@yoroi/portfolio

Version:

The Portfolio package of Yoroi SDK

89 lines (87 loc) 2.6 kB
import { Portfolio } from '@yoroi/types'; import { cacheManageMultiRequest, extractEntryCacheInfo, hasEntryValue, observerMaker } from '@yoroi/common'; import { freeze } from 'immer'; import { createCachedUnknownTokenInfo } from './helpers/create-cached-unknown-token-info'; export const portfolioTokenManagerMaker = function (_ref) { let { api, storage } = _ref; let { observer = observerMaker() } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const cachedInfosWithoutRecord = new Map(); const hydrate = _ref2 => { let { sourceId } = _ref2; // load only the cache info, drop the record storage.token.infos.all().map(extractEntryCacheInfo).filter(hasEntryValue).forEach(_ref3 => { let [id, value] = _ref3; return cachedInfosWithoutRecord.set(id, freeze(value)); }); observer.notify({ on: Portfolio.Event.ManagerOn.Hydrate, sourceId }); }; const sync = async _ref4 => { let { secondaryTokenIds, sourceId } = _ref4; const { records, unknownIds, updatedIds, isInvalidated } = await cacheManageMultiRequest({ request: async ids => api.tokenInfos(ids), cachedInfosWithoutRecord: freeze(new Map(cachedInfosWithoutRecord)), ids: secondaryTokenIds, unknownRecordFactory: createCachedUnknownTokenInfo, persistance: freeze({ save: storage.token.infos.save, read: storage.token.infos.read }) }); const recordsEntries = [...records.entries()]; recordsEntries.map(extractEntryCacheInfo).filter(hasEntryValue).forEach(_ref5 => { let [id, record] = _ref5; return cachedInfosWithoutRecord.set(id, freeze(record)); }); // if the cache was invalidated, notify if (isInvalidated) observer.notify({ on: Portfolio.Event.ManagerOn.Sync, ids: [...updatedIds, ...unknownIds], sourceId }); // when using subscriptions, or streams, read from storage base on callback args, not from this return return records; }; const clear = _ref6 => { let { sourceId } = _ref6; storage.token.infos.clear(); cachedInfosWithoutRecord.clear(); observer.notify({ on: Portfolio.Event.ManagerOn.Clear, sourceId }); }; const destroy = () => { observer.destroy(); }; return freeze({ hydrate, sync, subscribe: observer.subscribe, unsubscribe: observer.unsubscribe, observable$: observer.observable, api, destroy, clear }, true); }; //# sourceMappingURL=token-manager.js.map