AxiosStrategy.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import axios from "axios"
  2. import { decodeB64StringToArrayBuffer } from "../utils/b64"
  3. import { settingsStore } from "~/newstore/settings"
  4. let cancelSource = axios.CancelToken.source()
  5. export const cancelRunningAxiosRequest = () => {
  6. cancelSource.cancel()
  7. // Create a new cancel token
  8. cancelSource = axios.CancelToken.source()
  9. }
  10. const axiosWithProxy = async (req) => {
  11. try {
  12. const { data } = await axios.post(
  13. settingsStore.value.PROXY_URL || "https://proxy.hoppscotch.io",
  14. {
  15. ...req,
  16. wantsBinary: true,
  17. },
  18. {
  19. cancelToken: cancelSource.token,
  20. }
  21. )
  22. if (!data.success) {
  23. throw new Error(data.data.message || "Proxy Error")
  24. }
  25. if (data.isBinary) {
  26. data.data = decodeB64StringToArrayBuffer(data.data)
  27. }
  28. return data
  29. } catch (e) {
  30. // Check if the throw is due to a cancellation
  31. if (axios.isCancel(e)) {
  32. // eslint-disable-next-line no-throw-literal
  33. throw "cancellation"
  34. } else {
  35. console.error(e)
  36. throw e
  37. }
  38. }
  39. }
  40. const axiosWithoutProxy = async (req, _store) => {
  41. try {
  42. const res = await axios({
  43. ...req,
  44. cancelToken: (cancelSource && cancelSource.token) || "",
  45. responseType: "arraybuffer",
  46. })
  47. return res
  48. } catch (e) {
  49. if (axios.isCancel(e)) {
  50. // eslint-disable-next-line no-throw-literal
  51. throw "cancellation"
  52. } else {
  53. console.error(e)
  54. throw e
  55. }
  56. }
  57. }
  58. const axiosStrategy = (req) => {
  59. if (settingsStore.value.PROXY_ENABLED) {
  60. return axiosWithProxy(req)
  61. }
  62. return axiosWithoutProxy(req)
  63. }
  64. export const testables = {
  65. cancelSource,
  66. }
  67. export default axiosStrategy