The main server, and probably only repository in this org.
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.

92 lines
1.9 KiB

import {randId} from "./random";
import {fetchGet} from "./fetcher";
import {notNullish} from "./null";
const localData = {};
const callbacks = [];
export function subscribeToGroup(groupId, callback) {
const callbackId = randId();
callbacks.push({callbackId, groupId, callback});
if (groupId >= 0) {
if (notNullish(localData[groupId])) {
dispatch(localData[groupId]);
}
fetchOne(groupId);
} else {
const list = [];
for (let key in localData) {
if (localData.hasOwnProperty(key) && notNullish(localData[key])) {
list.push(localData[key]);
}
}
dispatch(list);
fetchAll();
}
console.log("subscribed");
console.dir(callbacks);
return callbackId;
}
export function unsubscribeFromGroup(callbackId) {
const callback = callbacks.find(c => c !== null && c.callbackId === callbackId);
const index = callbacks.indexOf(callback);
callbacks[index] = null;
console.log("unsubscribed");
console.dir(callbacks);
}
function fetchAll() {
fetchGet("/group/").then(({data, error}) => {
if (error === null) {
handleGroups(data);
}
});
}
function fetchOne(id) {
fetchGet(`/group/${id}`).then(({data, error}) => {
if (error === null) {
handleGroup(data);
}
});
}
function handleGroups(groups) {
groups.forEach(g => handleGroup(g));
for (let key in localData) {
if (localData.hasOwnProperty(key) && !groups.hasOwnProperty(key)) {
delete localData[key];
}
}
dispatch(groups);
}
function handleGroup(group) {
localData[group.id] = group;
dispatch(group);
}
function dispatch(data) {
if (Array.isArray(data)) {
callbacks
.filter(c => c !== null)
.filter(c => c.groupId === -1)
.forEach(c => c.callback(data));
} else {
callbacks
.filter(c => c !== null)
.filter(c => c.groupId === data.id)
.forEach(c => c.callback(data));
}
}