aboutsummaryrefslogtreecommitdiff
path: root/node_modules/koa-compose/index.js
diff options
context:
space:
mode:
Diffstat (limited to 'node_modules/koa-compose/index.js')
-rw-r--r--node_modules/koa-compose/index.js52
1 files changed, 52 insertions, 0 deletions
diff --git a/node_modules/koa-compose/index.js b/node_modules/koa-compose/index.js
new file mode 100644
index 00000000..431c0ffd
--- /dev/null
+++ b/node_modules/koa-compose/index.js
@@ -0,0 +1,52 @@
+'use strict'
+
+const Promise = require('any-promise')
+
+/**
+ * Expose compositor.
+ */
+
+module.exports = compose
+
+/**
+ * Compose `middleware` returning
+ * a fully valid middleware comprised
+ * of all those which are passed.
+ *
+ * @param {Array} middleware
+ * @return {Function}
+ * @api public
+ */
+
+function compose (middleware) {
+ if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
+ for (const fn of middleware) {
+ if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
+ }
+
+ /**
+ * @param {Object} context
+ * @return {Promise}
+ * @api public
+ */
+
+ return function (context, next) {
+ // last called middleware #
+ let index = -1
+ return dispatch(0)
+ function dispatch (i) {
+ if (i <= index) return Promise.reject(new Error('next() called multiple times'))
+ index = i
+ let fn = middleware[i]
+ if (i === middleware.length) fn = next
+ if (!fn) return Promise.resolve()
+ try {
+ return Promise.resolve(fn(context, function next () {
+ return dispatch(i + 1)
+ }))
+ } catch (err) {
+ return Promise.reject(err)
+ }
+ }
+ }
+}