You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.ts 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../app/actionTypes';
  2. import MiddlewareRegistry from '../redux/MiddlewareRegistry';
  3. import NetworkInfoService from './NetworkInfoService';
  4. import { _storeNetworkInfoCleanup, setNetworkInfo } from './actions';
  5. import { STORE_NAME } from './constants';
  6. import { ONLINE_STATE_CHANGED_EVENT } from './events';
  7. import logger from './logger';
  8. import type { NetworkInfo } from './types';
  9. /**
  10. * Middleware for 'base/net-info' feature.
  11. *
  12. * @param {Store} store - The redux store.
  13. * @returns {Function}
  14. */
  15. // eslint-disable-next-line no-unused-vars
  16. MiddlewareRegistry.register(({ dispatch, getState }) => next => action => {
  17. const result = next(action);
  18. switch (action.type) {
  19. case APP_WILL_MOUNT:
  20. if (NetworkInfoService.isSupported()) {
  21. const networkInfoService = new NetworkInfoService();
  22. const stop = () => {
  23. networkInfoService.stop();
  24. // @ts-ignore
  25. networkInfoService.removeAllListeners();
  26. };
  27. // @ts-ignore
  28. networkInfoService.addListener(
  29. ONLINE_STATE_CHANGED_EVENT,
  30. ({ isOnline, networkType, details }: NetworkInfo) => {
  31. logger.info('Network changed', JSON.stringify({
  32. isOnline,
  33. details,
  34. networkType
  35. }));
  36. dispatch(setNetworkInfo({
  37. isOnline,
  38. networkType,
  39. details
  40. }));
  41. });
  42. dispatch(_storeNetworkInfoCleanup(stop));
  43. networkInfoService.start();
  44. }
  45. break;
  46. case APP_WILL_UNMOUNT: {
  47. const { _cleanup } = getState()[STORE_NAME];
  48. if (_cleanup) {
  49. _cleanup();
  50. dispatch(_storeNetworkInfoCleanup(undefined));
  51. }
  52. }
  53. break;
  54. }
  55. return result;
  56. });