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.

107 lines
2.2 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. import {randId} from "./random";
  2. import {fetchDelete, fetchGet, fetchPatch, fetchPost} from "./fetcher";
  3. import {nullish} from "./null";
  4. const localData = {};
  5. const callbacks = [];
  6. export function subscribeToGroup(groupId, callback) {
  7. const callbackId = randId();
  8. callbacks.push({callbackId, groupId, callback});
  9. if (groupId >= 0) {
  10. fetchOne(groupId);
  11. } else {
  12. fetchAll();
  13. }
  14. return callbackId;
  15. }
  16. export function unsubscribeFromGroup(callbackId) {
  17. const callback = callbacks.find(c => c !== null && c.callbackId === callbackId);
  18. const index = callbacks.indexOf(callback);
  19. callbacks[index] = null;
  20. }
  21. export function addGroup(name) {
  22. fetchPost("/group/", {name}).then(({data, error}) => {
  23. if (error === null) {
  24. handleGroup(data);
  25. fetchAll();
  26. }
  27. })
  28. }
  29. export function deleteGroup(groupId) {
  30. fetchDelete(`/group/${groupId}`).then(({data, error}) => {
  31. if (error === null) {
  32. fetchAll();
  33. }
  34. });
  35. }
  36. export function saveGroupMetadata(groupId, name) {
  37. fetchPatch(`/group/${groupId}`, {name}).then(({data, error}) => {
  38. if (error === null) {
  39. fetchAll();
  40. }
  41. });
  42. }
  43. export function savePermissions(groupId, userId, permissions) {
  44. fetchPatch(`/group/${groupId}/permission/${userId}`, permissions).then(({data, error}) => {
  45. if (error === null) {
  46. fetchAll();
  47. }
  48. });
  49. }
  50. function fetchAll() {
  51. fetchGet("/group/").then(({data, error}) => {
  52. if (error === null) {
  53. handleGroups(data);
  54. }
  55. });
  56. }
  57. function fetchOne(id) {
  58. fetchGet(`/group/${id}`).then(({data, error}) => {
  59. if (error === null) {
  60. handleGroup(data);
  61. }
  62. });
  63. }
  64. function handleGroups(groups) {
  65. groups.forEach(g => handleGroup(g));
  66. for (let key in localData) {
  67. if (localData.hasOwnProperty(key) && nullish(groups.find(g => g.id === key))) {
  68. delete localData[key];
  69. }
  70. }
  71. dispatch(groups);
  72. }
  73. function handleGroup(group) {
  74. localData[group.id] = group;
  75. dispatch(group);
  76. }
  77. function dispatch(data) {
  78. if (Array.isArray(data)) {
  79. callbacks
  80. .filter(c => c !== null)
  81. .filter(c => c.groupId === -1)
  82. .forEach(c => c.callback(data));
  83. } else {
  84. callbacks
  85. .filter(c => c !== null)
  86. .filter(c => c.groupId === data.id)
  87. .forEach(c => c.callback(data));
  88. }
  89. }