useDownloadResponse.ts 1.3 KB

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