• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ivpusic/koa-routing: Manage koa routes on right way

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

ivpusic/koa-routing

开源软件地址:

https://github.com/ivpusic/koa-routing

开源编程语言:

JavaScript 98.9%

开源软件介绍:

koa-routing

Build Status Dependency Status

Installation

npm install koa-routing

Motivation

I wanted to separate my route definitions into multiple files. Also I wanted to make easier to specify route handlers, and execute some methods before some set of routes, for example ensuring that user is authenticated before doing some action. So I developed koa-r and koa-routing to achieve that. Final result is something like this:

/routing/index.js file

module.exports = function (app) {
  require('./users')(app.route('/api/users').before(authenticate));
};

/routing/users.js file

/**
 * /api/users
 */

module.exports = function (route) {
  /* GET /api/users */
  route.get(r('user', 'getUsers'));

  /* GET /api/users/logout */
  route.nested('/logout').get(r('user', 'logout'));
};

So here you can see that we are specifying handlers for route with r('module', 'method') pattern, and we are also following DRY principle when we define our routes.

If you like this idea, you are on right place.

Example

Let's define following routes:

  • /users [GET, POST, PUT],
  • /users/list [GET, PUT]

With koa-routing you can nest routes, and on that way you can follow DRY principle. Also koa-routing architecture help you to separate route handlers into multiple files. That example will be shown also.

var koa = require('koa'),
	routing = require('koa-routing');

var app = koa();
app.use(routing(app));

app.route('/users')
  .get(function * (next) {
    this.body = 'from get';
    yield next;
  })
  .post(function * (next) {
    this.body = 'from post';
    yield next;
  })
  .put(function * (next) {
    this.body = 'from put';
    yield next;
  })
  .nested('/list')
    .get(function * (next) {
      this.body = 'from users list GET';
      yield next;
    });
    .put(function * (next) {
      this.body = 'from users list PUT';
      yield next;
    });

app.listen(4000);

You should put koa-routing middleware after body parsers and simmilar middlewares which are preparing request for you, or passing an options object with a defer field setted to true.

As you can see, you can pass classic express route style, such as /user/:id, and after that you can read received values from this.params or this.request.params object.

You can pass also regex as route path.

API

route

koa-routing extends you application instance with route method. You can use that method for defining route path.

app.route('/users/:id');

HTTP methods

After you define your route, you need set HTTP methods for that route. In following example you need to replace someHTTPmethod with one of supported node HTTP methods. That can be GET, POST, PUT, etc...

app.route('route path').someHTTPmethod(handler);

So you can type something like:

var handler = function * () {
  yield next;
};

app.route('api/users').get(handler);

Keep in mind that every call returns router instance, so everything can be chained.

nested

Let's we say that you have for routes something like this:

  • /api/users/profile/data
  • /api/users/profile/image
  • etc.

You see that you are repeating /api/users/profile for every route, and we don't want to do that. koa-routing have nice solution for this with nested function.

// first you type fixed part
var route = app.route('/api/users/profile');

route.nested('/data')
  .get(function * (next) { yield next; });
  // here you can also define other HTTP operations, like POST, PUT, etc
  // example of put...
  .put(function * (next) { yield next; });

route.nested('/image')
  .get(function * (next) { yield next; });

Keep in mind that nested creates new route for you and returns created route. You can continue nesting routes. It is up to you.

before

You can define function which will be executed before each route method, and before all nested routes.

app.route('/someRoute')
	.before(function * (next) {
		this.status = 300;
	})
	.get(function * (next) {
		this.body = 'should not be here';
		this.status = 200;
		yield next;
	});

all

This function will be executed if there is no matching HTTP method.

app.route('/someRoute')
	.all(function * (next) {
		this.body = 'will catch GET/POST/PUT... etc';
		this.status = 200;
		yield next;
	})

Other features

Multiple middlewares

With koa-routing you can provide multiple middlewares for each route method:

app.route('/multipleMiddleware')
	.get(function * (next) {
		this.body = '1';
		this.status = 200;
		yield next;
	}, function * (next) {
		this.body = '2';
		yield next;
	});

If you go to this route you will receive 2 as a result, because request will be passed to each defined handler.

Options

app.use(routing(app,options));
  • defer Default is false. If true, serves after yield next, allowing any downstream middleware to respond first.

Contributing

Feel free to send pull request with some new awesome feature or some bug fix. But please provide some tests with your contribution.

License

MIT




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap