UNPKG

ice-frontend-react-mobx

Version:
62 lines (49 loc) 1.27 kB
const debug = require('debug')('ice:pollers:racks'); import { Rack } from '../models/Rack'; export default class RacksPoller { map = null; io = null; api = null; interval = null; constructor (map, io, api) { this.map = map; this.io = io; this.api = api; } startPolling () { debug('Starting rack polling'); this.interval = setInterval(this.poll, 500); } stopPolling () { debug('Stopping rack polling'); clearInterval(this.interval); } poll = () => { return this.api.getRacks().then((json) => { return this.updateFromJson(json); }).catch((error) => { return this.pollError(error); }); } updateFromJson (json) { if (Array.isArray(json)) { let newIds = []; json.forEach((rackJson) => { let rack = this.map.get(rackJson.id); if (!rack) { rack = new Rack(this.io); this.map.set(rackJson.id, rack); } rack.updateFromJson(rackJson); newIds.push(rack.id); }); 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 racks:', error); } }