useObjectLinks.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed } from 'vue'
  3. import {
  4. type LinkListQuery,
  5. type LinkUpdatesSubscriptionVariables,
  6. type LinkUpdatesSubscription,
  7. } from '#shared/graphql/types.ts'
  8. import QueryHandler from '#shared/server/apollo/handler/QueryHandler.ts'
  9. import type { ObjectLike } from '#shared/types/utils.ts'
  10. import getUuid from '#shared/utils/getUuid.ts'
  11. import { useLinkListQuery } from '../graphql/queries/linkList.api.ts'
  12. import { LinkUpdatesDocument } from '../graphql/subscriptions/linkUpdates.api.ts'
  13. import { useObjectLinkTypes } from './useObjectLinkTypes.ts'
  14. import type { Ref } from 'vue'
  15. export const useObjectLinks = (
  16. object: Ref<ObjectLike | undefined>,
  17. targetType: string,
  18. ) => {
  19. const { linkTypes } = useObjectLinkTypes()
  20. const objectId = computed(() => object.value?.id)
  21. const linkListQuery = new QueryHandler(
  22. useLinkListQuery(() => ({
  23. objectId: objectId.value,
  24. targetType,
  25. })),
  26. )
  27. const linkListQueryResult = linkListQuery.result()
  28. const linkListQueryLoading = linkListQuery.loading()
  29. linkListQuery.subscribeToMore<
  30. LinkUpdatesSubscriptionVariables,
  31. LinkUpdatesSubscription
  32. >(() => ({
  33. document: LinkUpdatesDocument,
  34. variables: {
  35. objectId: objectId.value,
  36. targetType,
  37. },
  38. updateQuery: (prev, { subscriptionData }) => {
  39. if (!subscriptionData.data?.linkUpdates.links) {
  40. return null as unknown as LinkListQuery
  41. }
  42. return {
  43. linkList: subscriptionData.data.linkUpdates.links,
  44. }
  45. },
  46. }))
  47. const links = computed(() => {
  48. if (!linkListQueryResult.value?.linkList) return []
  49. return linkListQueryResult.value?.linkList
  50. })
  51. const linkTypesWithLinks = computed(() => {
  52. return linkTypes
  53. .map((type) => ({
  54. ...type,
  55. id: getUuid(),
  56. links: links.value.filter((link) => link.type === type.value),
  57. }))
  58. .filter((type) => type.links.length > 0)
  59. })
  60. const hasLinks = computed(() => {
  61. return linkTypesWithLinks.value.some((type) => type.links.length > 0)
  62. })
  63. return {
  64. linkListIsLoading: linkListQueryLoading,
  65. linkTypesWithLinks,
  66. hasLinks,
  67. }
  68. }