Skip to content

Instantly share code, notes, and snippets.

@yamavol
Created June 13, 2020 05:07
Show Gist options
  • Save yamavol/2ca636a5a8d7c943c5dc545e3da70540 to your computer and use it in GitHub Desktop.
Save yamavol/2ca636a5a8d7c943c5dc545e3da70540 to your computer and use it in GitHub Desktop.
[Sample] accessing /about triggers checkAuth
const Koa = require('koa');
const Router = require('@koa/router');
function createRouter(prefix) {
return new Router({
prefix
});
}
function routeHandler(x) {
return async ctx => {
console.log(x);
ctx.body = `${x}`;
}
}
async function checkAuth(ctx, next) {
console.log('checkAuth');
// if (ctx.query['auth'] != "1") {
// throw new Error("not authed");
// }
await next();
}
function createAjaxRouter() {
// match for '/a(.*)'
const router = createRouter('/a');
router.use(checkAuth);
router.get('/1', routeHandler(1))
return router.routes();
}
function createIndexRouter() {
// match for '(.*)'
const router = createRouter();
router.get('/', routeHandler('index'));
router.get('/about', routeHandler('about'));
return router.routes();
}
function setRouter(app) {
// match for '(.*)'
const router = createRouter();
router.use(createAjaxRouter());
router.use(createIndexRouter());
// order of path in routes.router.stack =>
// ['/a(.*)', '/a/1', '/', '/about']
const routes = router.routes();
app.use(router.routes());
app.use(router.allowedMethods());
}
const app = new Koa();
setRouter(app);
app.listen(3010);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment