Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Last active Aug 17, 2017
Embed
What would you like to do?
koa-better-router subdirs + includes
// ˫ routes ˫ index.js
GET /
// ˫ routes ˫ api1 ˫ index.js
GET /api/v1/
GET /api/v1/x
// ˫ routes ˫ api1 ˫ a.js
PUT /api/v1/a/obj/:one/:two
GET /api/v1/a/obj/:one
// ˫ routes ˫ api1 ˫ b.js
PUT /api/v1/b/obj/:one/:two
GET /api/v1/b/
import Koa from 'koa';
import routeMiddleware from './routes';
const app = new Koa();
// ...
app.use(routeMiddleware());
// ...
app.listen(1337, '0.0.0.0');
import Router from 'koa-better-router';
const router = new Router({
//prefix: '/a', <---- will not be usable when inherited by extend()
}).loadMethods();
router.put('/a/obj/:one/:two', (ctx, next) => {
ctx.body = {success: true, params: ctx.params};
return next();
})
.get('/a/obj/:one', (ctx, next) => {
let val = true;
ctx.body = {success: true, params: ctx.params, result: { value: val }};
return next();
});
// ....
export default router;
import Router from 'koa-better-router';
const router = new Router({
//prefix: '/b', <---- will not be usable when inherited by extend()
}).loadMethods();
router.put('/b/obj/:one/:two', (ctx, next) => {
ctx.body = {success: true, params: ctx.params};
return next();
})
.get('/b/', (ctx, next) => {
let val = [1,2,3];
ctx.body = {success: true, result: { value: val }};
return next();
});
// ....
export default router;
import Router from 'koa-better-router';
const router = new Router({
prefix: '/api/v1'
}).loadMethods();
router.get('/', (ctx, next) => {
ctx.body = router.routes.map( (e) => e.path );
return next();
});
router.get('/x', (ctx, next) => {
ctx.body = 'list ...';
return next();
});
// looses all prefix info from within them, so the included ones need the full url string,
// including its supposed prefix, so we do not need to hack-update it into the url
import a from './a.js';
router.extend(a); // looses all prefix info from within them
import b from './b.js';
router.extend(b); // looses all prefix info from within them
export default router;
import Router from 'koa-better-router';
const router = new Router().loadMethods();
router.get('/', (ctx, next) => {
ctx.body = `Server v1.0.0`;
return next();
});
export default router;
import Router from 'koa-better-router';
// Import all routes
import app from './app';
import api1 from './api1';
const router = new Router(/* no prefix here! */);
// add routes - hack (keep prefixes, but does not merge them with local one, but local one would be '/' anyways) !!
app.routes.forEach( (e) =>
router.routes.push(e)
);
api1.routes.forEach( (e) =>
router.routes.push(e)
);
// output routes
router.routes.forEach( (e) => console.log(e.method, e.path) );
export default () => {return router.middleware();} // do not loose object ref when exporting the func -> wrapt into a func.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment