2.1.0 • Published 7 years ago

koa-route-dispatcher v2.1.0

Weekly downloads
12
License
MIT
Repository
github
Last release
7 years ago

koa-route-dispatcher

NPM

Uber simple route middleware for koa. (koa-route)

support JSON format

const dispatcher = require('koa-route-dispatcher');
const routesMap = require('./routes/map.json'); //map.js
app.use(dispatcher(routesMap));

Syntax

dispatcher(routesMap [, controllersPath='/workingDirectory/controllers/']);

If you need a full-featured solution check out koa-router, a Koa clone of express-resource.

Installation

$ npm install koa-route-dispatcher

Example

// app.js
const Koa = require('koa');
const app = new Koa();
const dispatcher = require('koa-route-dispatcher');
const routesMap = require('./routes/map.json');

app.use(dispatcher(routesMap, './controllers/'));
app.listen(3000);

console.log('listening on port 3000');
// reoutes/map.json
[
  {"path": "/pets", "method": "get", "controller": "pets.list", "opts": {}},
  {"path": "/pets/:name", "method": "get", "controller": "pets.show"},
  {"path": "/async/pets", "method": "get", "controller": "/async/pets.list", "opts": {}},
  {"path": "/async/pets/:name", "method": "get", "controller": "/async/pets.show", "opts": {}}
]
// controllers/async/pets.js
function getDBAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        tobi: { name: 'tobi', species: 'ferret' },
        loki: { name: 'loki', species: 'ferret' },
        jane: { name: 'jane', species: 'ferret' }
      });
    }, 2000);
  });
}

module.exports = {
  list: async (ctx) => {
    const db = await getDBAfter2Seconds();

    const names = Object.keys(db);
    ctx.body = 'pets: ' + names.join(', ');
  },

  show: function* (name) {
    const ctx = this;
    const db = yield getDBAfter2Seconds();

    const pet = db[name];
    if (!pet) return ctx.throw(404, 'cannot find that pet');
    ctx.body = pet.name + ' is a ' + pet.species;
  }
};

License

MIT

2.1.0

7 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.1.6

10 years ago

1.1.5

10 years ago

1.1.4

10 years ago

1.1.3

10 years ago

1.1.2

10 years ago

1.1.1

10 years ago

1.0.2

10 years ago

1.0.0

10 years ago