You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
1.6 KiB
78 lines
1.6 KiB
import {randId} from "./random";
|
|
import {notNullish, nullish} from "./null";
|
|
import {fetchGet} from "./fetcher";
|
|
|
|
const localData = {};
|
|
const callbacks = [];
|
|
|
|
export function subscribeToLight(lightId, callback) {
|
|
const callbackId = randId();
|
|
|
|
callbacks.push({callbackId, lightId, callback});
|
|
|
|
if (lightId >= 0) {
|
|
if (notNullish(localData[lightId])) {
|
|
dispatch(localData[lightId]);
|
|
}
|
|
|
|
fetchOne(lightId);
|
|
} else {
|
|
const list = [];
|
|
for (let key in localData) {
|
|
if (localData.hasOwnProperty(key) && notNullish(localData[key])) {
|
|
list.push(localData[key]);
|
|
}
|
|
}
|
|
dispatch(list);
|
|
|
|
fetchAll();
|
|
}
|
|
}
|
|
|
|
function fetchAll() {
|
|
fetchGet(`/light/`).then(({data, error}) => {
|
|
if (error === null) {
|
|
handleLights(data);
|
|
}
|
|
});
|
|
}
|
|
|
|
function fetchOne(id) {
|
|
fetchGet(`/light/${id}`).then(({data, error}) => {
|
|
if (error === null) {
|
|
handleLight(data);
|
|
}
|
|
});
|
|
}
|
|
|
|
function handleLights(lights) {
|
|
lights.forEach(l => handleLight(l));
|
|
|
|
for (let key in localData) {
|
|
if (localData.hasOwnProperty(key) && nullish(lights.find(l => l.id === key))) {
|
|
delete localData[key];
|
|
}
|
|
}
|
|
|
|
dispatch(lights);
|
|
}
|
|
|
|
function handleLight(light) {
|
|
localData[light.id] = light;
|
|
|
|
dispatch(light);
|
|
}
|
|
|
|
function dispatch(data) {
|
|
if (Array.isArray(data)) {
|
|
callbacks
|
|
.filter(c => c !== null)
|
|
.filter(c => c.lightId === -1)
|
|
.forEach(c => c.callback(data));
|
|
} else {
|
|
callbacks
|
|
.filter(c => c !== null)
|
|
.filter(c => c.lightId === data.id)
|
|
.forEach(c => c.callback(data));
|
|
}
|
|
}
|