ExtensionStrategy.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import * as TE from "fp-ts/TaskEither"
  2. import { pipe } from "fp-ts/function"
  3. import { NetworkResponse, NetworkStrategy } from "../network"
  4. import { browserIsChrome, browserIsFirefox } from "../utils/userAgent"
  5. export const hasExtensionInstalled = () =>
  6. typeof window.__POSTWOMAN_EXTENSION_HOOK__ !== "undefined"
  7. export const hasChromeExtensionInstalled = () =>
  8. hasExtensionInstalled() && browserIsChrome()
  9. export const hasFirefoxExtensionInstalled = () =>
  10. hasExtensionInstalled() && browserIsFirefox()
  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 extensionStrategy: NetworkStrategy = (req) =>
  20. pipe(
  21. TE.Do,
  22. // Storeing backup timing data in case the extension does not have that info
  23. TE.bind("backupTimeDataStart", () => TE.of(new Date().getTime())),
  24. // Run the request
  25. TE.bind("response", () =>
  26. TE.tryCatch(
  27. () =>
  28. window.__POSTWOMAN_EXTENSION_HOOK__.sendRequest({
  29. ...req,
  30. wantsBinary: true,
  31. }) as Promise<NetworkResponse>,
  32. (err) => err as any
  33. )
  34. ),
  35. // Inject backup time data if not present
  36. TE.map(({ backupTimeDataStart, response }) => ({
  37. ...response,
  38. config: {
  39. timeData: {
  40. startTime: backupTimeDataStart,
  41. endTime: new Date().getTime(),
  42. },
  43. ...response.config,
  44. },
  45. })),
  46. TE.orElse((e) =>
  47. e !== "cancellation" && e.response
  48. ? TE.right(e.response as NetworkResponse)
  49. : TE.left(e)
  50. )
  51. )
  52. export default extensionStrategy