ExtensionStrategy.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { decodeB64StringToArrayBuffer } from "../utils/b64"
  2. import { settingsStore } from "~/newstore/settings"
  3. export const hasExtensionInstalled = () =>
  4. typeof window.__POSTWOMAN_EXTENSION_HOOK__ !== "undefined"
  5. export const hasChromeExtensionInstalled = () =>
  6. hasExtensionInstalled() &&
  7. /Chrome/i.test(navigator.userAgent) &&
  8. /Google/i.test(navigator.vendor)
  9. export const hasFirefoxExtensionInstalled = () =>
  10. hasExtensionInstalled() && /Firefox/i.test(navigator.userAgent)
  11. export const cancelRunningExtensionRequest = () => {
  12. if (
  13. hasExtensionInstalled() &&
  14. window.__POSTWOMAN_EXTENSION_HOOK__.cancelRunningRequest
  15. ) {
  16. window.__POSTWOMAN_EXTENSION_HOOK__.cancelRunningRequest()
  17. }
  18. }
  19. const extensionWithProxy = async (req) => {
  20. const backupTimeDataStart = new Date().getTime()
  21. const res = await window.__POSTWOMAN_EXTENSION_HOOK__.sendRequest({
  22. method: "post",
  23. url: settingsStore.value.PROXY_URL || "https://proxy.hoppscotch.io/",
  24. data: {
  25. ...req,
  26. wantsBinary: true,
  27. },
  28. })
  29. const backupTimeDataEnd = new Date().getTime()
  30. const parsedData = JSON.parse(res.data)
  31. if (!parsedData.success) {
  32. throw new Error(parsedData.data.message || "Proxy Error")
  33. }
  34. if (parsedData.isBinary) {
  35. parsedData.data = decodeB64StringToArrayBuffer(parsedData.data)
  36. }
  37. if (!(res && res.config && res.config.timeData)) {
  38. res.config = {
  39. timeData: {
  40. startTime: backupTimeDataStart,
  41. endTime: backupTimeDataEnd,
  42. },
  43. }
  44. }
  45. parsedData.config = res.config
  46. return parsedData
  47. }
  48. const extensionWithoutProxy = async (req) => {
  49. const backupTimeDataStart = new Date().getTime()
  50. const res = await window.__POSTWOMAN_EXTENSION_HOOK__.sendRequest({
  51. ...req,
  52. wantsBinary: true,
  53. })
  54. const backupTimeDataEnd = new Date().getTime()
  55. if (!(res && res.config && res.config.timeData)) {
  56. res.config = {
  57. timeData: {
  58. startTime: backupTimeDataStart,
  59. endTime: backupTimeDataEnd,
  60. },
  61. }
  62. }
  63. return res
  64. }
  65. const extensionStrategy = (req) => {
  66. if (settingsStore.value.PROXY_ENABLED) {
  67. return extensionWithProxy(req)
  68. }
  69. return extensionWithoutProxy(req)
  70. }
  71. export default extensionStrategy