InterceptorManager.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. * @param {Object} options The options for the interceptor, synchronous and runWhen
  13. *
  14. * @return {Number} An ID used to remove interceptor later
  15. */
  16. use(fulfilled, rejected, options) {
  17. this.handlers.push({
  18. fulfilled,
  19. rejected,
  20. synchronous: options ? options.synchronous : false,
  21. runWhen: options ? options.runWhen : null,
  22. });
  23. return this.handlers.length - 1;
  24. }
  25. /**
  26. * Remove an interceptor from the stack
  27. *
  28. * @param {Number} id The ID that was returned by `use`
  29. *
  30. * @returns {void}
  31. */
  32. eject(id) {
  33. if (this.handlers[id]) {
  34. this.handlers[id] = null;
  35. }
  36. }
  37. /**
  38. * Clear all interceptors from the stack
  39. *
  40. * @returns {void}
  41. */
  42. clear() {
  43. if (this.handlers) {
  44. this.handlers = [];
  45. }
  46. }
  47. /**
  48. * Iterate over all the registered interceptors
  49. *
  50. * This method is particularly useful for skipping over any
  51. * interceptors that may have become `null` calling `eject`.
  52. *
  53. * @param {Function} fn The function to call for each interceptor
  54. *
  55. * @returns {void}
  56. */
  57. forEach(fn) {
  58. utils.forEach(this.handlers, function forEachHandler(h) {
  59. if (h !== null) {
  60. fn(h);
  61. }
  62. });
  63. }
  64. }
  65. export default InterceptorManager;