项目作者: gbahamondezc

项目描述 :
Koa@2.x middleware to load routes from files and directories using koa-router module
高级语言: JavaScript
项目地址: git://github.com/gbahamondezc/koa-load-routes.git
创建时间: 2016-03-19T20:00:10Z
项目社区:https://github.com/gbahamondezc/koa-load-routes

开源协议:MIT License

下载


koa-load-routes

NPM version Build Status Dependency Status Coverage Status

Koa middleware to load routes from files and directories using koa-router module

Warning

  • Node.js 8.0 and koa@2.x or latest are required to use this module.
  • Since v2.0 koa-load-routes not support Generator Functions anymore (in favor of Async Functions).
  • Since v3.0 path option must be a absolute path
  • Since v3.0 firstMiddleware option was removed in favor of middlewares option.

Installation

  1. $ npm install --save koa-load-routes

or

  1. $ yarn add koa-load-routes
Options
  • String -> path (required)

    • Path from where the module will try to load the routes, if is a file, it will read the routes defined just inside of the file, otherwise, if is a directory, will read all .js files in the directory and load the routes inside each one.
  • Boolean -> recursive (optional, default: false)

    • If this argument is true the module will search route files recursive trhoug directories.
  • Array[Function|AsyncFunction] -> middlewares (optional)

    • A list of middlewares which will be added to each route loaded, can be Array of async functions or a normal functions or mixed, this middlewares will be attached previous to each route, useful by example for authentication middlewares.
  • String -> base (optional)

    • Adds the “base” string at the start of each loaded route url.
  • Array[any] -> args (optional)

    • Arguments to be pased inside the route main function, each array elements are passed as a independent argument (see examples below).
  • String -> suffix (optional, default: ‘.js’)

    • If this argument is passed the module will load only the files which ends with the passed suffix + .js, by default if suffix is not supplied will try to load all files with .js extension.

Usage

app.js
  1. const Koa = require('koa');
  2. const loader = require('koa-load-routes');
  3. const authMiddleware = require('./auth-middleware');
  4. const path = require('path');
  5. // Some module containing business logic and db access
  6. const Interactors = require('./interactors');
  7. var app = new Koa();
  8. // Loading public routes
  9. app.use(route({
  10. path: `${path.resolve()}/src/resources/public`,
  11. recursive: true,
  12. // Add /api/ at start of each loaded endpoint
  13. base: 'api',
  14. // Load files only ending with route.js
  15. suffix: 'route',
  16. // Injecting your business logic module
  17. args: [Interactors]
  18. }));
  19. // Loading private routes with auth middleware
  20. app.use(route({
  21. path: `${path.resolve()}/src/resources/account`,
  22. recursive: true,
  23. base: 'api',
  24. suffix: 'route',
  25. middlewares : [authMiddleware()],
  26. args: [Interactors]
  27. }));
  28. app.listen(3000, () => {
  29. console.log('server started at http://127.0.0.1:3000/');
  30. });
src/resources/public/login.route.js
  1. module.exports = function (Interactors) {
  2. // Authentication endpoint
  3. this.post('/login', async ctx => {
  4. let userAccount = await Interactors.userAccount
  5. .getByEmail(ctx.request.body.email);
  6. if (!userAccount) {
  7. ctx.throw(404, 'Account not found');
  8. }
  9. if (ctx.body.password !== userAccount.password) {
  10. ctx.throw(403, 'Wrong Email/Password combination');
  11. }
  12. /*
  13. * You can create some kind of auth token here to
  14. * send it in body with user account info.
  15. * This is just an example
  16. */
  17. ctx.body = userAccount;
  18. });
  19. // Other possible routes examples
  20. this.get('/hello', (ctx, next) => {
  21. ctx.body = 'Hello world';
  22. return next();
  23. });
  24. // Routes chain
  25. this.get('/hello2', (ctx, next) => {
  26. ctx.body = 'hello world 2';
  27. })
  28. .get('/hello3', (ctx, next) => {
  29. ctx.body = 'hello world 3';
  30. });
  31. // Multiple middlewares
  32. this.post('/hello4', (ctx, next) => {
  33. console.log('im the first one');
  34. return next();
  35. },
  36. (ctx, next) => {
  37. ctx.body = 'yey!';
  38. });
  39. };

License

MIT © Gonzalo Bahamondez