UNPKG

@hsui/request

Version:

Hundsun frontend runtime request framework

77 lines (74 loc) 2.3 kB
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray"; import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck"; import _createClass from "@babel/runtime/helpers/esm/createClass"; import { noop } from './utils'; /** * @class - MiddlewareManager * @classdesc - manager of middlewares */ export var MiddlewareManager = /*#__PURE__*/function () { function MiddlewareManager(type) { _classCallCheck(this, MiddlewareManager); this.type = type; this.middlewares = []; this.finalHook = noop; } _createClass(MiddlewareManager, [{ key: "final", value: function final(hook) { this.finalHook = hook; } }, { key: "concat", value: function concat(middlewares) { this.middlewares = this.middlewares.concat(middlewares); } }, { key: "push", value: function push(middleware) { this.middlewares.push(middleware); } // just run and return nothing }, { key: "justRun", value: function justRun() { this.args = Array.prototype.slice.call(arguments); var _this = this; var fn = function fn(index) { if (index < this.middlewares.length) { this.middlewares[index].apply(null, [].concat(_toConsumableArray(this.args), [function () { fn.call(_this, ++index); }])); } else { this.finalHook.apply(null, this.args); } }; fn.call(_this, 0); } // run middlewares and return a promise }, { key: "runAndReturn", value: function runAndReturn() { this.args = Array.prototype.slice.call(arguments); var _this = this; return new Promise(function (resolve, reject) { var fn = function fn(index) { if (index < this.middlewares.length) { try { this.middlewares[index].apply(null, [].concat(_toConsumableArray(this.args), [function () { fn.call(_this, ++index); }])); } catch (error) { reject(error); } } else { // final hook should return a promise too this.finalHook.apply(null, this.args).then(resolve).catch(reject); } }; fn.call(_this, 0); }); } }]); return MiddlewareManager; }();