aboutsummaryrefslogtreecommitdiff
path: root/node_modules/koa-connect/index.js
diff options
context:
space:
mode:
authorruki <waruqi@gmail.com>2018-11-08 00:38:48 +0800
committerruki <waruqi@gmail.com>2018-11-07 21:53:09 +0800
commit26105034da4fcce7ac883c899d781f016559310d (patch)
treec459a5dc4e3aa0972d9919033ece511ce76dd129 /node_modules/koa-connect/index.js
parent2c77f00f1a7ecb6c8192f9c16d3b2001b254a107 (diff)
downloadxmake-docs-26105034da4fcce7ac883c899d781f016559310d.tar.gz
xmake-docs-26105034da4fcce7ac883c899d781f016559310d.zip
switch to vuepress
Diffstat (limited to 'node_modules/koa-connect/index.js')
-rw-r--r--node_modules/koa-connect/index.js38
1 files changed, 38 insertions, 0 deletions
diff --git a/node_modules/koa-connect/index.js b/node_modules/koa-connect/index.js
new file mode 100644
index 00000000..20139f1e
--- /dev/null
+++ b/node_modules/koa-connect/index.js
@@ -0,0 +1,38 @@
+/**
+ * If the middleware function does declare receiving the `next` callback
+ * assume that it's synchronous and invoke `next` ourselves
+ */
+function noCallbackHandler(ctx, connectMiddleware, next) {
+ connectMiddleware(ctx.req, ctx.res)
+ return next()
+}
+
+/**
+ * The middleware function does include the `next` callback so only resolve
+ * the Promise when it's called. If it's never called, the middleware stack
+ * completion will stall
+ */
+function withCallbackHandler(ctx, connectMiddleware, next) {
+ return new Promise((resolve, reject) => {
+ connectMiddleware(ctx.req, ctx.res, err => {
+ if (err) reject(err)
+ else resolve(next())
+ })
+ })
+}
+
+/**
+ * Returns a Koa middleware function that varies its async logic based on if the
+ * given middleware function declares at least 3 parameters, i.e. includes
+ * the `next` callback function
+ */
+function koaConnect(connectMiddleware) {
+ const handler = connectMiddleware.length < 3
+ ? noCallbackHandler
+ : withCallbackHandler
+ return function koaConnect(ctx, next) {
+ return handler(ctx, connectMiddleware, next)
+ }
+}
+
+module.exports = koaConnect