aircox/assets/src/live.js
Chris Tactic 55123c386d #132 | #121: backoffice / dev-1.0-121 (#131)
cfr #121

Co-authored-by: Christophe Siraut <d@tobald.eu.org>
Co-authored-by: bkfox <thomas bkfox net>
Co-authored-by: Thomas Kairos <thomas@bkfox.net>
Reviewed-on: #131
Co-authored-by: Chris Tactic <ctactic@noreply.git.radiocampus.be>
Co-committed-by: Chris Tactic <ctactic@noreply.git.radiocampus.be>
2024-04-28 22:02:09 +02:00

84 lines
2.2 KiB
JavaScript

import {setEcoInterval} from './utils';
import Model from './model';
export default class Live {
constructor({url,timeout=10,src=""}={}) {
this.url = url;
this.timeout = timeout;
this.src = src;
this.interval = null
this.promise = null
this.items = []
this.current = null
}
//-- data refreshing
drop() {
this.promise = null;
}
/**
* Fetch data from server.
*
* @param {Object} options
* @param {Function} options.then: call this method on fetch, `this` passed as argument.
* @return {Promise} Promise resolving to fetched items.
*/
fetch({then=null}={}) {
const promise = fetch(this.url).then(response =>
response.ok ? response.json()
: Promise.reject(response)
).then(data => {
data = data.results
data.forEach(item => {
if(item.start) item.start = new Date(item.start)
if(item.end) item.end = new Date(item.end)
})
this.items = data
const now = new Date()
let item = data.find(it => it.start && (it.start <= now < it.end)) ||
data.length ? data[0] : null;
if(item) {
item.src = this.src
this.current = new Model(item)
}
else
this.current = null
if(then)
then(this)
return this.items
})
this.promise = promise;
return promise;
}
_refresh(options={}) {
const promise = this.fetch(options);
promise.then(() => {
if(promise != this.promise)
return [];
})
return promise
}
/**
* Refresh live info every `this.timeout`.
* @param {Object} options: arguments passed to `this.fetch`.
*/
refresh(options={}) {
if(this.interval !== null)
return
this._refresh(options)
this.interval = setEcoInterval(() => this._refresh(options), this.timeout*1000)
return this.interval
}
stopRefresh() {
this.interval !== null && clearInterval(this.interval)
}
}