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.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* @flow */
  2. import XHRInterceptor from 'react-native/Libraries/Network/XHRInterceptor';
  3. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../../app';
  4. import { MiddlewareRegistry } from '../../base/redux';
  5. import {
  6. _ADD_NETWORK_REQUEST,
  7. _REMOVE_ALL_NETWORK_REQUESTS,
  8. _REMOVE_NETWORK_REQUEST
  9. } from './actionTypes';
  10. /**
  11. * Middleware which captures app startup and conference actions in order to
  12. * clear the image cache.
  13. *
  14. * @returns {Function}
  15. */
  16. MiddlewareRegistry.register(store => next => action => {
  17. const result = next(action);
  18. switch (action.type) {
  19. case APP_WILL_MOUNT:
  20. _startNetInterception(store);
  21. break;
  22. case APP_WILL_UNMOUNT:
  23. _stopNetInterception(store);
  24. break;
  25. }
  26. return result;
  27. });
  28. /**
  29. * Starts intercepting network requests. Only XHR requests are supported at the
  30. * moment.
  31. *
  32. * Ongoing request information is kept in redux, and it's removed as soon as a
  33. * given request is complete.
  34. *
  35. * @param {Object} store - The redux store.
  36. * @private
  37. * @returns {void}
  38. */
  39. function _startNetInterception({ dispatch }) {
  40. XHRInterceptor.setOpenCallback((method, url, xhr) => dispatch({
  41. type: _ADD_NETWORK_REQUEST,
  42. request: xhr,
  43. // The following are not really necessary read anywhere at the time of
  44. // this writing but are provided anyway if the reducer chooses to
  45. // remember them:
  46. method,
  47. url
  48. }));
  49. XHRInterceptor.setResponseCallback((...args) => dispatch({
  50. type: _REMOVE_NETWORK_REQUEST,
  51. // XXX The XHR is the last argument of the responseCallback.
  52. request: args[args.length - 1]
  53. }));
  54. XHRInterceptor.enableInterception();
  55. }
  56. /**
  57. * Stops intercepting network requests.
  58. *
  59. * @param {Object} store - The redux store.
  60. * @private
  61. * @returns {void}
  62. */
  63. function _stopNetInterception({ dispatch }) {
  64. XHRInterceptor.disableInterception();
  65. dispatch({
  66. type: _REMOVE_ALL_NETWORK_REQUESTS
  67. });
  68. }