UNPKG

ice-frontend-react-mobx

Version:
62 lines (49 loc) 1.3 kB
const debug = require('debug')('ice:pollers:groups'); import { Group } from '../models/Group'; export default class GroupsPoller { map = null; io = null; api = null; interval = null; constructor (map, io, api) { this.map = map; this.io = io; this.api = api; } startPolling () { debug('Starting group polling'); this.interval = setInterval(this.poll, 500); } stopPolling () { debug('Stopping group polling'); clearInterval(this.interval); } poll = () => { return this.api.getGroups().then((json) => { return this.updateFromJson(json); }).catch((error) => { return this.pollError(error); }); } updateFromJson (json) { if (Array.isArray(json)) { let newIds = []; json.forEach((groupJson) => { newIds.push(groupJson.id); let group = this.map.get(groupJson.id); if (!group) { group = new Group(this.io); this.map.set(groupJson.id, group); } group.updateFromJson(groupJson); }); Array.from(this.map.keys()).filter((id) => (newIds.indexOf(id) === -1)).forEach((id) => { this.map.get(id).dispose(); this.map.delete(id); }); } } pollError (error) { debug('Error polling groups:', error); } }