useImageUpload.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { useFormUploadCacheAddMutation } from '#shared/components/Form/fields/FieldFile/graphql/mutations/uploadCache/add.api.ts'
  3. import { parseGraphqlId } from '#shared/graphql/utils.ts'
  4. import { MutationHandler } from '#shared/server/apollo/handler/index.ts'
  5. import type { ImageFileData, ImageFileSource } from '#shared/utils/files.ts'
  6. import { useFileUploadProcessing } from '../../composables/useFileUploadProcessing.ts'
  7. export const useImageUpload = (
  8. formId: string,
  9. name: string,
  10. inline: boolean,
  11. ) => {
  12. const addFileMutation = new MutationHandler(useFormUploadCacheAddMutation({}))
  13. const { setFileUploadProcessing, removeFileUploadProcessing } =
  14. useFileUploadProcessing(formId, name)
  15. const uploadImage = (
  16. files: ImageFileData[],
  17. successCallback: (files: ImageFileSource[]) => void,
  18. ) => {
  19. setFileUploadProcessing()
  20. return addFileMutation
  21. .send({
  22. formId,
  23. files: files.map((file) => ({
  24. name: file.name,
  25. type: file.type,
  26. content: file.content,
  27. inline,
  28. })),
  29. })
  30. .then((response) => {
  31. const uploadedFiles = response?.formUploadCacheAdd?.uploadedFiles.map(
  32. (file) => {
  33. return {
  34. name: file.name,
  35. type: file.type,
  36. src: `/api/v1/attachments/${parseGraphqlId(file.id).id}`,
  37. }
  38. },
  39. ) as ImageFileSource[]
  40. successCallback(uploadedFiles)
  41. })
  42. .finally(() => {
  43. removeFileUploadProcessing()
  44. })
  45. }
  46. return { uploadImage }
  47. }