Created
August 12, 2018 22:07
-
-
Save andrejewski/3cd51e4f858cdcfc55b6f5885d3f3c9a to your computer and use it in GitHub Desktop.
Koa middleware utilities [WIP]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// koatil/index | |
function group (middlewares) { | |
return function _group (ctx, next) { | |
return runGroup(middlewares, 0, ctx, next) | |
} | |
} | |
function runGroup (routes, routeIndex, ctx, next) { | |
const route = routes[routeIndex] | |
return route | |
? route.callback(ctx, exitGroup => { | |
if (exitGroup === false) { | |
return next() | |
} | |
return runGroup(routes, routeIndex + 1, ctx, next) | |
}) | |
: next() | |
} | |
function when (predicate, left, right) { | |
if (right) { | |
return function _either (ctx, next) { | |
return predicate(ctx) | |
? left(ctx, next) | |
: right(ctx, next) | |
} | |
} | |
return function _if (ctx, next) { | |
return predicate(ctx) | |
? left(ctx, next) | |
: next() | |
} | |
} | |
exports.group = group | |
exports.when = when | |
// koatil/routing | |
function method (methodType, middleware) { | |
return when( | |
ctx => ctx.request.method === methodType, | |
middleware | |
) | |
} | |
function path (pathExpression, middleware) { | |
/* | |
if isMatch | |
muck ctx with routeParams | |
run middleware | |
unmuck ctx with routeParams | |
continue | |
*/ | |
} | |
function route (methodType, pathExpression, middleware) { | |
return method(methodType, path(pathExpression, middleware)) | |
} | |
function withinPath (pathExpression, middleware) { | |
return pathExpression(pathExpression, group([ | |
withUrl(ctx.url.slice(1)), | |
middleware | |
])) | |
} | |
function pFinally (promise, callback) { | |
if (promise && promise.then) { | |
return promise | |
.then(value => { | |
callback() | |
return value | |
}) | |
.catch(error => { | |
callback() | |
throw error | |
}) | |
} | |
callback() | |
return promise | |
} | |
function withUrl (url) { | |
return function _withUrl (ctx, next) { | |
const oldUrl = ctx.url | |
ctx.url = url | |
return pFinally(next(), () => { | |
ctx.url = oldUrl | |
}) | |
} | |
} | |
function withMethod (method) { | |
return function _withUrl (ctx, next) { | |
const oldMethod = ctx.url | |
ctx.method = method | |
return pFinally(next(), () => { | |
ctx.method = oldMethod | |
}) | |
} | |
} | |
exports.method = method | |
exports.path = path | |
exports.route = route | |
exports.withinPath = withinPath | |
exports.withUrl = withUrl | |
exports.withMethod = withMethod |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment