InterceptorManager.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. import utils from './../utils.js';
  3. class InterceptorManager {
  4. constructor() {
  5. this.handlers = [];
  6. }
  7. /**
  8. * Add a new interceptor to the stack
  9. *
  10. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  11. * @param {Function} rejected The function to handle `reject` for a `Promise`
  12. *
  13. * @return {Number} An ID used to remove interceptor later
  14. */
  15. use(fulfilled, rejected, options) {
  16. this.handlers.push({
  17. fulfilled,
  18. rejected,
  19. synchronous: options ? options.synchronous : false,
  20. runWhen: options ? options.runWhen : null
  21. });
  22. return this.handlers.length - 1;
  23. }
  24. /**
  25. * Remove an interceptor from the stack
  26. *
  27. * @param {Number} id The ID that was returned by `use`
  28. *
  29. * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
  30. */
  31. eject(id) {
  32. if (this.handlers[id]) {
  33. this.handlers[id] = null;
  34. }
  35. }
  36. /**
  37. * Clear all interceptors from the stack
  38. *
  39. * @returns {void}
  40. */
  41. clear() {
  42. if (this.handlers) {
  43. this.handlers = [];
  44. }
  45. }
  46. /**
  47. * Iterate over all the registered interceptors
  48. *
  49. * This method is particularly useful for skipping over any
  50. * interceptors that may have become `null` calling `eject`.
  51. *
  52. * @param {Function} fn The function to call for each interceptor
  53. *
  54. * @returns {void}
  55. */
  56. forEach(fn) {
  57. utils.forEach(this.handlers, function forEachHandler(h) {
  58. if (h !== null) {
  59. fn(h);
  60. }
  61. });
  62. }
  63. }
  64. export default InterceptorManager;