useDownloadResponse.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import * as S from "fp-ts/string"
  2. import * as RNEA from "fp-ts/ReadonlyNonEmptyArray"
  3. import { pipe } from "fp-ts/function"
  4. import { Ref } from "@nuxtjs/composition-api"
  5. import { refAutoReset } from "@vueuse/core"
  6. import { useI18n, useToast } from "~/helpers/utils/composables"
  7. export type downloadResponseReturnType = (() => void) | Ref<any>
  8. export default function useDownloadResponse(
  9. contentType: string,
  10. responseBody: Ref<string | ArrayBuffer>
  11. ): {
  12. downloadIcon: Ref<string>
  13. downloadResponse: () => void
  14. } {
  15. const downloadIcon = refAutoReset<"download" | "check">("download", 1000)
  16. const toast = useToast()
  17. const t = useI18n()
  18. const downloadResponse = () => {
  19. const dataToWrite = responseBody.value
  20. const file = new Blob([dataToWrite], { type: contentType })
  21. const a = document.createElement("a")
  22. const url = URL.createObjectURL(file)
  23. a.href = url
  24. // TODO: get uri from meta
  25. a.download = pipe(
  26. url,
  27. S.split("/"),
  28. RNEA.last,
  29. S.split("#"),
  30. RNEA.head,
  31. S.split("?"),
  32. RNEA.head
  33. )
  34. document.body.appendChild(a)
  35. a.click()
  36. downloadIcon.value = "check"
  37. toast.success(`${t("state.download_started")}`)
  38. setTimeout(() => {
  39. document.body.removeChild(a)
  40. URL.revokeObjectURL(url)
  41. }, 1000)
  42. }
  43. return {
  44. downloadIcon,
  45. downloadResponse,
  46. }
  47. }