koa-compose 源码解析

发布时间 2023-04-30 13:28:28作者: TangTaue

Koa-Compose 函数解析

 1 'use strict'
 2 
 3 /**
 4  * Expose compositor.
 5  */
 6 
 7 module.exports = compose
 8 
 9 /**
10  * Compose `middleware` returning
11  * a fully valid middleware comprised
12  * of all those which are passed.
13  *
14  * @param {Array} middleware
15  * @return {Function}
16  * @api public
17  */
18 
19 function compose (middleware) {
20   if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
21   for (const fn of middleware) {
22     if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
23   }
24 
25   /**
26    * @param {Object} context
27    * @return {Promise}
28    * @api public
29    */
30 
31   return function (context, next) {
32     // last called middleware #
33     let index = -1
34     return dispatch(0)
35     function dispatch (i) {
36       if (i <= index) return Promise.reject(new Error('next() called multiple times'))
37       index = i
38       let fn = middleware[i]
39       if (i === middleware.length) fn = next
40       if (!fn) return Promise.resolve()
41       try {
42         return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
43       } catch (err) {
44         return Promise.reject(err)
45       }
46     }
47   }
48 }