useFieldExternalDataSourceWrapper.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { AutocompleteSearchObjectAttributeExternalDataSourceDocument } from '#shared/components/Form/fields/FieldExternalDataSource/graphql/queries/autocompleteSearchObjectAttributeExternalDataSource.api.ts'
  3. import type { ObjectLike } from '#shared/types/utils.ts'
  4. import type { ExternalDataSourceProps } from './types.ts'
  5. import type { AutocompleteSelectValue } from '../FieldAutocomplete/types.ts'
  6. import type { JsonValue } from 'type-fest'
  7. import type { Ref } from 'vue'
  8. export const useFieldExternalDataSourceWrapper = (
  9. context: Ref<ExternalDataSourceProps['context']>,
  10. ) => {
  11. const additionalQueryParams = () => {
  12. const additionalQueryParams: Record<string, JsonValue> = {
  13. object: context.value.object,
  14. attributeName: context.value.node.name,
  15. }
  16. const { searchTemplateRenderContext, formId, object } = context.value
  17. const templateRenderContext: Record<string, JsonValue> = {}
  18. // Add the main entity object id from the current object.
  19. const entityObject = context.value.node.at('$root')?.context
  20. ?.initialEntityObject as ObjectLike
  21. if (entityObject) {
  22. templateRenderContext[`${object.toLowerCase()}Id`] = entityObject.id
  23. }
  24. // Add additional data from the given search context information.
  25. if (searchTemplateRenderContext) {
  26. const additionaltemplateRenderContext =
  27. searchTemplateRenderContext(formId, entityObject) || {}
  28. Object.assign(templateRenderContext, additionaltemplateRenderContext)
  29. }
  30. additionalQueryParams.templateRenderContext = templateRenderContext
  31. return additionalQueryParams
  32. }
  33. return {
  34. actionIcon: 'search',
  35. gqlQuery: AutocompleteSearchObjectAttributeExternalDataSourceDocument,
  36. additionalQueryParams,
  37. complexValue: true,
  38. // use getter to return new value each time
  39. get clearValue() {
  40. return {}
  41. },
  42. initialOptionBuilder: (_: ObjectLike, value: AutocompleteSelectValue) =>
  43. value,
  44. }
  45. }