import {randId} from "./random"; import {fetchDelete, fetchGet, fetchPatch, fetchPost} from "./fetcher"; import {nullish} from "./null"; const localData = {}; const callbacks = []; export function subscribeToGroup(groupId, callback) { const callbackId = randId(); callbacks.push({callbackId, groupId, callback}); if (groupId >= 0) { fetchOne(groupId); } else { fetchAll(); } return callbackId; } export function unsubscribeFromGroup(callbackId) { const callback = callbacks.find(c => c !== null && c.callbackId === callbackId); const index = callbacks.indexOf(callback); callbacks[index] = null; } export function addGroup(name) { fetchPost("/group/", {name}).then(({data, error}) => { if (error === null) { handleGroup(data); fetchAll(); } }) } export function deleteGroup(groupId) { fetchDelete(`/group/${groupId}`).then(({data, error}) => { if (error === null) { fetchAll(); } }); } export function saveGroupMetadata(groupId, name) { fetchPatch(`/group/${groupId}`, {name}).then(({data, error}) => { if (error === null) { fetchAll(); } }); } export function savePermissions(groupId, userId, permissions) { fetchPatch(`/group/${groupId}/permission/${userId}`, permissions).then(({data, error}) => { if (error === null) { fetchAll(); } }); } 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) && nullish(groups.find(g => g.id === 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)); } }