UNPKG

2.44 kBJavaScriptView Raw
1"use strict";
2/*
3 * co-compose
4 *
5 * (c) Harminder Virk <virk@adonisjs.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10Object.defineProperty(exports, "__esModule", { value: true });
11exports.Runnable = void 0;
12/**
13 * Default final handler resolves the middleware chain right away
14 */
15const DEFAULT_FINAL_HANDLER = {
16 fn: () => Promise.resolve(),
17 args: [],
18};
19/**
20 * The default executor to execute middlewares. This method assumes middleware
21 * as functions and calls them right away
22 */
23const DEFAULT_EXECUTOR = (fn, params) => fn(...params);
24/**
25 * Runnable to execute an array of functions in sequence. The queue is
26 * advanced only when the current function calls `next`.
27 *
28 * @example
29 * ```js
30 * const runner = new Runnable([async function fn1 (params, next) {
31 * }])
32 * ```
33 */
34class Runnable {
35 constructor(list) {
36 this.list = list;
37 this.index = 0;
38 this.params = [];
39 this.executorFn = DEFAULT_EXECUTOR;
40 this.registeredFinalHandler = DEFAULT_FINAL_HANDLER;
41 }
42 /**
43 * Invoke one middleware at a time. Middleware fns will be executed
44 * recursively until `next` is invoked.
45 *
46 * If one method doesn't call `next`, then the chain will be finished
47 * automatically.
48 */
49 invoke() {
50 const fn = this.list[this.index++];
51 /**
52 * Empty stack
53 */
54 if (!fn) {
55 return this.registeredFinalHandler.fn(...this.registeredFinalHandler.args);
56 }
57 return this.executorFn(fn, this.params);
58 }
59 /**
60 * Final handler to be executed, when chain ends successfully
61 */
62 finalHandler(fn, args) {
63 this.registeredFinalHandler = { fn, args };
64 return this;
65 }
66 /**
67 * Define custom resolver, which is invoked for all the middleware.
68 * If this method is defined, then default executor is not called
69 * and it's the responsibility of this method to call the
70 * middleware and pass params to it
71 */
72 executor(fn) {
73 this.executorFn = fn;
74 return this;
75 }
76 /**
77 * Start the middleware queue and pass params to it. The `params`
78 * array will be passed as spread arguments.
79 */
80 async run(params) {
81 this.params = params.concat(this.invoke.bind(this));
82 return this.invoke();
83 }
84}
85exports.Runnable = Runnable;