UNPKG

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