Socket
Socket
Sign inDemoInstall

koa-router

Package Overview
Dependencies
Maintainers
1
Versions
91
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

koa-router - npm Package Compare versions

Comparing version 1.1.2 to 1.2.2

21

index.js

@@ -18,2 +18,7 @@ /**

// Transform methods to uppercase
methods.forEach(function(method, i, arr) {
arr[i] = method.toUpperCase();
});
/**

@@ -33,3 +38,3 @@ * Initialize Router with given `app`.

for (var len = methods.length, i=0; i<len; i++) {
this.routes[methods[i].toUpperCase()] = [];
this.routes[methods[i]] = [];
}

@@ -40,8 +45,16 @@ // Expose `router.route` as `app.map`

methods.forEach(function(method) {
app[method] = function() {
app[method.toLowerCase()] = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift([method.toUpperCase()]);
app.map.apply(app, args);
args.unshift([method]);
return app.map.apply(app, args);
};
});
// Alias `app.delete` as `app.del`
app.del = app['delete'];
// Register route with all methods
app.all = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(methods);
return app.map.apply(app, args);
};
// `Resource` factory

@@ -48,0 +61,0 @@ app.resource = function() {

2

package.json

@@ -9,3 +9,3 @@ {

"author": "Alex Mingoia <talk@alexmingoia.com>",
"version": "1.1.2",
"version": "1.2.2",
"keywords": ["koa", "middleware", "router", "route"],

@@ -12,0 +12,0 @@ "dependencies": {

@@ -5,3 +5,3 @@ # Router middleware for [koa](https://github.com/koajs/koa)

* REST routing using `app.get`, `app.post`, etc.
* REST routing using `app.get`, `app.put`, `app.post`, etc.
* Rails-like resource routing, with nested resources.

@@ -15,3 +15,3 @@ * Named parameters.

npm install koa-router
npm install --global koa-router

@@ -22,36 +22,59 @@ ## Usage

var koa = require('koa');
var router = require('koa-router');
var koa = require('koa')
, router = require('koa-router')
, app = koa();
var app = koa();
app.use(router(app));
app.get('/users/:id', function *(id) {
var user = yield User.findOne(id);
this.body = user;
});
### Map specific routes
### app.verb(path, callback, [callback...])
You can map specific routes using methods corresponding to the HTTP verb, such as `app.get` or `app.post`.
`app.verb()` methods are created for the app used to create the router,
where **verb** is one of the HTTP verbs, such as `app.get()` or `app.post()`.
app.get('/', function *(next) {
this.body = 'Hello world!';
});
Multiple callbacks may be given, and each one will be called sequentially.
This allows you to modify the context or route parameters for subsequent
callbacks.
### Named parameters
Route paths will be translated to regular expressions used to match requests.
Query strings will not be considered when matching requests.
Named route parameters are captured and passed as arguments to the route callback. They are also available in the app context using `this.params`.
##### Named parameters
Named route parameters are captured and passed as arguments to the route callback.
They are also available in the app context using `this.params`.
app.get('/:category/:title', function *(category, title, next) {
console.log(this.params);
// { category: 'programming', title: 'How to Node' }
console.log(this.paramsArray);
// [ 'category', 'title' ]
// => { category: 'programming', title: 'how-to-node' }
});
### Multiple methods
##### Regular expressions
You can map routes to multiple HTTP methods using `app.map`:
Control route matching exactly by specifying a regular expression instead of
a path string when creating the route. For example, it might be useful to match
date formats for a blog, such as `/blog/2013-09-04`:
app.map(['GET', 'POST', '/come/get/some', function *(next) {
this.body = 'Here it is!';
app.get(/^\/blog\/\d{4}-\d{2}-\d{2}\/?$/i, function *(next) {
// ...
});
##### Multiple methods
You can map routes to multiple HTTP methods using `app.map()`:
app.map(['GET', 'POST'], '/', function *(next) {
// ...
});
You can map to all methods use `app.all()`:
app.all('/', function *(next) {
// ...
});
### Resource routing

@@ -70,3 +93,3 @@

#### Action mapping
##### Action mapping

@@ -83,3 +106,3 @@ Actions are then mapped accordingly:

#### Top-level resource
##### Top-level resource

@@ -100,3 +123,3 @@ Omit the resource name to specify a top-level resource:

#### Auto-loading
##### Auto-loading

@@ -122,3 +145,3 @@ Automatically load requested resources by specifying the `load` action

#### Nesting
##### Nesting

@@ -125,0 +148,0 @@ Resources can be nested using `resource.add()`:

@@ -107,3 +107,3 @@ /**

case 'destroy':
route = app.delete(base + ':' + id, load ? [load, action] : action);
route = app.del(base + ':' + id, load ? [load, action] : action);
break;

@@ -110,0 +110,0 @@ }

/**
* Initialize a new Route with given `methods`, `pattern`, and `callbacks`.
*
* @param {String} method
* @param {String} pattern
* @param {Function} callbacks
* @param {Mixed} method HTTP verb string or array of verbs.
* @param {Mixed} pattern Path string or regular expression.
* @param {Mixed} callbacks Route callback function or array of functions.
* @return {Route}

@@ -12,9 +12,9 @@ * @api public

function Route(methods, pattern, callbacks) {
if (typeof methods === 'string') methods = [methods];
if (typeof callbacks === 'function') callbacks = [callbacks];
if (typeof methods == 'string') methods = [methods];
if (typeof callbacks == 'function') callbacks = [callbacks];
this.methods = methods;
this.pattern = pattern;
this.pattern = pattern instanceof RegExp ? pattern.source : pattern;
this.regexp = Route.patternToRegExp(pattern);
this.paramsArray = [];
this.paramNames = Route.patternToParamNames(pattern);
this.paramNames = Route.patternToParamNames(this.pattern);
this.params = {};

@@ -91,2 +91,3 @@ this.callbacks = callbacks;

Route.patternToRegExp = function(pattern) {
if (pattern instanceof RegExp) return pattern;
pattern = pattern

@@ -93,0 +94,0 @@ .replace(/\//g, '\\/') // Escape slashes.

@@ -12,2 +12,3 @@ /**

var http = require('http');
var methods = require('methods');

@@ -34,11 +35,27 @@ describe('module', function() {

app.use(router(app));
app.get('/match/this', function *(next) {
methods.forEach(function(method) {
app.should.have.property(method.toLowerCase());
});
app.get('/:category/:title', function *(category, title, next) {
category.should.equal('programming');
title.should.equal('how-to-node');
this.status = 204;
done();
});
request(http.createServer(app.callback()))
.get('/match/this')
app.post('/:category', function *(category, next) {
category.should.equal('programming');
this.status = 204;
});
var server = http.createServer(app.callback());
request(server)
.get('/programming/how-to-node')
.expect(204)
.end(function(err, res) {
if (err) return done(err);
request(server)
.post('/programming')
.expect(204)
.end(function(err, res) {
if (err) return done(err);
done();
});
});

@@ -64,3 +81,3 @@ });

};
app.get('/match/this', function *(next) {
app.get('/', function *(next) {
var version = yield readVersion();

@@ -71,3 +88,3 @@ this.status = 204;

request(http.createServer(app.callback()))
.get('/match/this')
.get('/')
.expect(204)

@@ -78,2 +95,16 @@ .end(function(err, res) {

});
it('should provide `app.all()` to route all methods', function(done) {
var app = koa();
app.use(router(app));
var route = app.all('/', function *(next) {
this.status = 204;
});
methods.forEach(function(method) {
method = method.toUpperCase();
app.routes.should.have.property(method);
app.routes[method].should.include(route);
});
done();
});
});

@@ -40,5 +40,5 @@ /**

threads.base.should.equal('/forums/:forum/threads/');
should.exist(app.routes.GET[2]);
app.routes.GET[2].should.be.a('object');
app.routes.GET[2].should.have.property('pattern', '/forums/:forum/threads/');
should.exist(app.routes.GET[1]);
app.routes.GET[1].should.be.a('object');
app.routes.GET[1].should.have.property('pattern', '/forums/:forum/threads/');
done();

@@ -45,0 +45,0 @@ });

@@ -53,2 +53,17 @@ /**

it('should support regular expression route paths', function(done) {
var app = koa();
app.use(router(app));
app.get(/^\/blog\/\d{4}-\d{2}-\d{2}\/?$/i, function *(next) {
this.status = 204;
});
request(http.createServer(app.callback()))
.get('/blog/2013-04-20')
.expect(204)
.end(function(err) {
if (err) return done(err);
done();
});
});
it('should support multiple callbacks', function(done) {

@@ -55,0 +70,0 @@ var app = koa();

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc