ExtensionStrategy.ts 1.7 KB

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