Koa@2.x middleware to load routes from files and directories using koa-router module
Koa middleware to load routes from files and directories using koa-router module
$ npm install --save koa-load-routes
or
$ yarn add koa-load-routes
String -> path (required)
Boolean -> recursive (optional, default: false)
Array[Function|AsyncFunction] -> middlewares (optional)
String -> base (optional)
Array[any] -> args (optional)
String -> suffix (optional, default: ‘.js’)
const Koa = require('koa');
const loader = require('koa-load-routes');
const authMiddleware = require('./auth-middleware');
const path = require('path');
// Some module containing business logic and db access
const Interactors = require('./interactors');
var app = new Koa();
// Loading public routes
app.use(route({
path: `${path.resolve()}/src/resources/public`,
recursive: true,
// Add /api/ at start of each loaded endpoint
base: 'api',
// Load files only ending with route.js
suffix: 'route',
// Injecting your business logic module
args: [Interactors]
}));
// Loading private routes with auth middleware
app.use(route({
path: `${path.resolve()}/src/resources/account`,
recursive: true,
base: 'api',
suffix: 'route',
middlewares : [authMiddleware()],
args: [Interactors]
}));
app.listen(3000, () => {
console.log('server started at http://127.0.0.1:3000/');
});
module.exports = function (Interactors) {
// Authentication endpoint
this.post('/login', async ctx => {
let userAccount = await Interactors.userAccount
.getByEmail(ctx.request.body.email);
if (!userAccount) {
ctx.throw(404, 'Account not found');
}
if (ctx.body.password !== userAccount.password) {
ctx.throw(403, 'Wrong Email/Password combination');
}
/*
* You can create some kind of auth token here to
* send it in body with user account info.
* This is just an example
*/
ctx.body = userAccount;
});
// Other possible routes examples
this.get('/hello', (ctx, next) => {
ctx.body = 'Hello world';
return next();
});
// Routes chain
this.get('/hello2', (ctx, next) => {
ctx.body = 'hello world 2';
})
.get('/hello3', (ctx, next) => {
ctx.body = 'hello world 3';
});
// Multiple middlewares
this.post('/hello4', (ctx, next) => {
console.log('im the first one');
return next();
},
(ctx, next) => {
ctx.body = 'yey!';
});
};
MIT © Gonzalo Bahamondez