npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-routing

v1.3.1

Published

Routing middleware for Koa

Downloads

34

Readme

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