AxiosStrategy.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import axios from "axios"
  2. import { v4 } from "uuid"
  3. import { decodeB64StringToArrayBuffer } from "../utils/b64"
  4. import { settingsStore } from "~/newstore/settings"
  5. import { JsonFormattedError } from "~/helpers/utils/JsonFormattedError"
  6. let cancelSource = axios.CancelToken.source()
  7. export const cancelRunningAxiosRequest = () => {
  8. cancelSource.cancel()
  9. // Create a new cancel token
  10. cancelSource = axios.CancelToken.source()
  11. }
  12. const axiosWithProxy = async (req) => {
  13. try {
  14. let proxyReqPayload = {
  15. ...req,
  16. wantsBinary: true,
  17. }
  18. const headers = {}
  19. if (req.data instanceof FormData) {
  20. const key = `proxyRequestData-${v4()}` // generate UniqueKey
  21. headers["multipart-part-key"] = key
  22. const formData = proxyReqPayload.data
  23. proxyReqPayload.data = "" // discard formData
  24. formData.append(key, JSON.stringify(proxyReqPayload)) // append axiosRequest to form
  25. proxyReqPayload = formData
  26. }
  27. const { data } = await axios.post(
  28. settingsStore.value.PROXY_URL || "https://proxy.hoppscotch.io",
  29. proxyReqPayload,
  30. {
  31. headers,
  32. cancelToken: cancelSource.token,
  33. }
  34. )
  35. if (!data.success) {
  36. throw new Error(data.data.message || "Proxy Error")
  37. }
  38. if (data.isBinary) {
  39. data.data = decodeB64StringToArrayBuffer(data.data)
  40. }
  41. return data
  42. } catch (e) {
  43. // Check if the throw is due to a cancellation
  44. if (axios.isCancel(e)) {
  45. // eslint-disable-next-line no-throw-literal
  46. throw "cancellation"
  47. } else {
  48. throw e
  49. }
  50. }
  51. }
  52. const axiosWithoutProxy = async (req, _store) => {
  53. try {
  54. const res = await axios({
  55. ...req,
  56. cancelToken: (cancelSource && cancelSource.token) || "",
  57. responseType: "arraybuffer",
  58. })
  59. return res
  60. } catch (e) {
  61. if (axios.isCancel(e)) {
  62. // eslint-disable-next-line no-throw-literal
  63. throw "cancellation"
  64. } else if (e.response?.data) {
  65. throw new JsonFormattedError(
  66. JSON.parse(Buffer.from(e.response.data, "base64").toString("utf8"))
  67. )
  68. } else {
  69. throw e
  70. }
  71. }
  72. }
  73. const axiosStrategy = (req) => {
  74. if (settingsStore.value.PROXY_ENABLED) {
  75. return axiosWithProxy(req)
  76. }
  77. return axiosWithoutProxy(req)
  78. }
  79. export const testables = {
  80. cancelSource,
  81. }
  82. export default axiosStrategy