UNPKG

data-provider-temporary

Version:

Library that helps with server-to-client synchronization of data

98 lines (78 loc) 2.23 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class DataProvider { constructor({ id, ref, rawOnData, onData, initialData }) { this.id = id; this.ref = ref; this.rawOnData = rawOnData; this.onData = onData; this.userConfigs = {}; this.loaded = false; if (initialData !== undefined) { this.loaded = true; this.onData(initialData); } } updateUser(userId, { polling = Infinity, needed = true, rawGetData, getData }) { let needFetch = false; if (rawGetData != null && !_lodash2.default.isEqual(rawGetData, this.rawGetData)) { needFetch = true; this.rawGetData = rawGetData; this.getData = getData; this.loaded = false; } let oldPolling = this.polling(); this.userConfigs[userId] = { polling, needed }; if (this.polling() < oldPolling) { needFetch = true; } if (!this.loaded && !this.timer) { needFetch = true; } if (needFetch) { this.fetch(); } } removeUser(userId) { delete this.userConfigs[userId]; } polling() { return _lodash2.default.min([..._lodash2.default.values(this.userConfigs).map(({ polling }) => polling), Infinity]); } needed() { return _lodash2.default.reduce(_lodash2.default.values(this.userConfigs).map(({ needed }) => needed), (v1, v2) => v1 || v2, false); } canceled() { return _lodash2.default.isEmpty(this.userConfigs); } scheduleNextFetch() { if (this.polling() === Infinity) { return; } this.timer = setTimeout(() => { this.fetch(); }, this.polling()); } fetch() { if (this.canceled()) { return null; } if (this.timer) { clearTimeout(this.timer); } return this.getData().then(data => { if (!this.canceled()) { this.loaded = true; this.onData(data); } }).catch(e => { console.error(e); // eslint-disable-line no-console }).then(() => this.scheduleNextFetch()); } } exports.default = DataProvider;