useObjectAttributes.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, toRefs } from 'vue'
  3. import type { FormSchemaField } from '#shared/components/Form/types.ts'
  4. import type {
  5. ObjectManagerFrontendAttribute,
  6. EnumObjectManagerObjects,
  7. } from '#shared/graphql/types.ts'
  8. import { QueryHandler } from '#shared/server/apollo/handler/index.ts'
  9. import getFieldFromAttribute from '../form/getFieldFromAttribute.ts'
  10. import { useObjectManagerFrontendAttributesQuery } from '../graphql/queries/objectManagerFrontendAttributes.api.ts'
  11. import { useObjectAttributesStore } from '../stores/objectAttributes.ts'
  12. export const useObjectAttributes = (object: EnumObjectManagerObjects) => {
  13. const objectAttributes = useObjectAttributesStore()
  14. // Check if we have already a instance of the requested object
  15. // attribute object, otherwise trigger the query.
  16. if (!objectAttributes.objectAttributesObjectLookup[object]) {
  17. const handler = new QueryHandler(
  18. useObjectManagerFrontendAttributesQuery({
  19. object,
  20. }),
  21. )
  22. const attributesRaw = handler.result()
  23. const attributesLoading = handler.loading()
  24. const attributes = computed(() => {
  25. return (
  26. attributesRaw.value?.objectManagerFrontendAttributes?.attributes || []
  27. )
  28. })
  29. const screens = computed(() => {
  30. return (
  31. attributesRaw.value?.objectManagerFrontendAttributes?.screens.reduce(
  32. (screens: Record<string, string[]>, screen) => {
  33. screens[screen.name] = screen.attributes
  34. return screens
  35. },
  36. {},
  37. ) || {}
  38. )
  39. })
  40. const attributesLookup = computed(() => {
  41. const lookup: Map<string, ObjectManagerFrontendAttribute> = new Map()
  42. attributes.value?.forEach((attribute) =>
  43. lookup.set(attribute.name, attribute),
  44. )
  45. return lookup
  46. })
  47. const formFieldAttributesLookup = computed(() => {
  48. const lookup: Map<string, FormSchemaField> = new Map()
  49. attributes.value?.forEach((attribute) =>
  50. lookup.set(attribute.name, getFieldFromAttribute(object, attribute)),
  51. )
  52. return lookup
  53. })
  54. objectAttributes.objectAttributesObjectLookup[object] = {
  55. attributes,
  56. screens,
  57. attributesLookup,
  58. formFieldAttributesLookup,
  59. loading: attributesLoading,
  60. }
  61. }
  62. return {
  63. ...toRefs(objectAttributes.objectAttributesObjectLookup[object]),
  64. }
  65. }