useEvents.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { onBeforeUnmount, ref } from "vue";
  2. import { useWebsocketStore } from "@/stores/websocket";
  3. export const useEvents = () => {
  4. const websocketStore = useWebsocketStore();
  5. const readySubscriptions = ref({});
  6. const subscriptions = ref({});
  7. const onReady = async callback => {
  8. const uuid = await websocketStore.onReady(callback);
  9. readySubscriptions.value[uuid] = { callback };
  10. return uuid;
  11. };
  12. const removeReadyCallback = uuid => {
  13. if (!readySubscriptions.value[uuid]) return;
  14. websocketStore.removeReadyCallback(uuid);
  15. delete readySubscriptions.value[uuid];
  16. };
  17. const subscribe = async (channel, callback) => {
  18. const uuid = await websocketStore.subscribe(channel, callback);
  19. subscriptions.value[uuid] = { channel, callback };
  20. return uuid;
  21. };
  22. const subscribeMany = async channels => {
  23. const _subscriptions = await websocketStore.subscribeMany(channels);
  24. await Promise.all(
  25. Object.entries(_subscriptions).map(
  26. async ([uuid, { channel, callback }]) => {
  27. subscriptions.value[uuid] = { channel, callback };
  28. }
  29. )
  30. );
  31. return Object.fromEntries(
  32. Object.entries(_subscriptions).map(([uuid, { channel }]) => [
  33. channel,
  34. uuid
  35. ])
  36. );
  37. };
  38. const unsubscribe = async uuid => {
  39. if (!subscriptions.value[uuid]) return;
  40. const { channel } = subscriptions.value[uuid];
  41. await websocketStore.unsubscribe(channel, uuid);
  42. delete subscriptions.value[uuid];
  43. };
  44. const unsubscribeMany = async uuids => {
  45. const _subscriptions = Object.fromEntries(
  46. Object.entries(subscriptions.value)
  47. .filter(([uuid]) => uuids.includes(uuid))
  48. .map(([uuid, { channel }]) => [uuid, channel])
  49. );
  50. await websocketStore.unsubscribeMany(_subscriptions);
  51. return Promise.all(
  52. uuids.map(async uuid => {
  53. delete subscriptions.value[uuid];
  54. })
  55. );
  56. };
  57. onBeforeUnmount(async () => {
  58. await Promise.allSettled(
  59. Object.keys(subscriptions.value).map(uuid => unsubscribe(uuid))
  60. );
  61. await Promise.allSettled(
  62. Object.keys(readySubscriptions.value).map(async uuid =>
  63. removeReadyCallback(uuid)
  64. )
  65. );
  66. });
  67. return {
  68. readySubscriptions,
  69. subscriptions,
  70. onReady,
  71. removeReadyCallback,
  72. subscribe,
  73. subscribeMany,
  74. unsubscribe,
  75. unsubscribeMany
  76. };
  77. };