macro.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { without } from 'lodash-es'
  3. import { defineStore } from 'pinia'
  4. import { computed, nextTick, ref, toValue } from 'vue'
  5. import { useMacrosUpdateSubscription } from '#shared/graphql/subscriptions/macrosUpdate.api.ts'
  6. import type {
  7. MacrosQuery,
  8. MacrosQueryVariables,
  9. } from '#shared/graphql/types.ts'
  10. import QueryHandler from '#shared/server/apollo/handler/QueryHandler.ts'
  11. import SubscriptionHandler from '#shared/server/apollo/handler/SubscriptionHandler.ts'
  12. export const useMacroStore = defineStore('macro', () => {
  13. const usageKeys = ref<string[]>([])
  14. const queryByUsageKey = new Map<
  15. string,
  16. QueryHandler<MacrosQuery, MacrosQueryVariables>
  17. >()
  18. const activate = (
  19. usageKey: string,
  20. query: QueryHandler<MacrosQuery, MacrosQueryVariables>,
  21. ) => {
  22. usageKeys.value.push(usageKey)
  23. queryByUsageKey.set(usageKey, query)
  24. }
  25. const enabled = computed(() => usageKeys.value.length > 0)
  26. const macroSubscription = new SubscriptionHandler(
  27. useMacrosUpdateSubscription(() => ({ enabled })),
  28. )
  29. macroSubscription.onResult((data) => {
  30. if (!data.data?.macrosUpdate.macroUpdated) return
  31. const refetchFor: Record<string, boolean> = {}
  32. queryByUsageKey.forEach((query) => {
  33. const { groupId } = toValue(query.operationResult.variables) ?? {}
  34. // Skip refetching of duplicate queries with the same group ID.
  35. if (!groupId || refetchFor[groupId]) return
  36. query.refetch()
  37. refetchFor[groupId] = true
  38. })
  39. })
  40. const deactivate = (usageKey: string) => {
  41. if (!usageKeys.value.includes(usageKey)) return
  42. nextTick(() => {
  43. usageKeys.value = without(usageKeys.value, usageKey)
  44. queryByUsageKey.delete(usageKey)
  45. })
  46. }
  47. return {
  48. usageKeys,
  49. activate,
  50. deactivate,
  51. }
  52. })