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.4.3 to 1.5.3

lib/resource.js

138

index.js

@@ -8,138 +8,2 @@ /**

/**
* Dependencies
*/
var methods = require('methods')
, parse = require('url').parse
, Resource = require('./resource')
, Route = require('./route');
/**
* Initialize Router with given `app`.
*
* @param {Application} app
* @return {Router}
* @api public
*/
function Router(app) {
if (!(this instanceof Router)) {
var router = new Router(app);
return router.middleware();
}
app.router = this;
this.app = app;
// Create container for routes
this.routes = app.routes = {};
for (var len = methods.length, i=0; i<len; i++) {
this.routes[methods[i]] = [];
}
// Expose `router.route` as `app.map`
app.map = this.route;
// Alias methods for `router.route`
methods.forEach(function(method) {
app[method] = function() {
var args = Array.prototype.slice.call(arguments);
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
app.resource = function() {
var args = Array.prototype.slice.call(arguments);
args.push(this);
var resource = Object.create(Resource.prototype);
Resource.apply(resource, args);
return resource;
};
};
/**
* Expose `Router`
*/
module.exports = Router;
/**
* Router prototype
*/
var router = Router.prototype;
/**
* Router middleware factory. Returns router middleware which dispatches route
* callbacks corresponding to the request.
*
* @param {Function} next
* @return {Function}
* @api public
*/
router.middleware = function() {
var router = this;
return function(next) {
return function *() {
// Find matching route
var route = router.match(this.req.method, parse(this.req.url).path);
// Dispatch route callbacks
if (route) {
router.app.context({ route: route, params: route.params });
for (var len = route.callbacks.length, i=0; i<len; i++) {
yield route.callbacks[i].apply(
this,
route.paramsArray.concat([next])
);
}
}
else {
yield next;
}
};
};
};
/**
* Match given `method` and `path` and return corresponding route.
*
* @param {String} method
* @param {String} path
* @return {Route}
* @api public
*/
router.match = function(method, path) {
var routes = this.routes[method.toLowerCase()];
for (var len = routes.length, i=0; i<len; i++) {
if (routes[i].match(method, path)) return routes[i];
}
};
/**
* Route given `callbacks` to request `method` and path `pattern` combination.
*
* @param {Array} methods Array of HTTP methods/verbs
* @param {String} pattern
* @param {Function} callbacks
* @return {Route}
* @api public
*/
router.route = function(methods, pattern, callbacks) {
if (arguments.length > 3) {
callbacks = Array.prototype.slice.call(arguments, 2);
}
var route = new Route(methods, pattern, callbacks);
for (var len = methods.length, i=0; i<len; i++) {
this.routes[methods[i]].push(route);
}
return route;
};
module.exports = require('./lib/router');

@@ -9,5 +9,6 @@ {

"author": "Alex Mingoia <talk@alexmingoia.com>",
"version": "1.4.3",
"version": "1.5.3",
"keywords": ["koa", "middleware", "router", "route"],
"dependencies": {
"extend": "1.2.0",
"lingo": "0.0.5",

@@ -14,0 +15,0 @@ "methods": "0.0.1",

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

* Multiple route callbacks.
* Multiple routers.

@@ -36,16 +37,27 @@ ## Install

You may also instantiate the router separately from mounting the middleware:
You can use multiple routers and sets of routes by omitting the `app`
argument. For example, separate routers for two versions of an API:
var router = new Router(app);
var APIv1 = new Router();
var APIv2 = new Router();
app.use(router.middleware());
APIv1.get('/sign-in', function *() {
// ...
});
APIv2.get('/sign-in', function *() {
// ...
});
app.use(mount('/v1', APIv1.middleware()));
app.use(mount('/v2', APIv2.middleware()));
### app.verb(path, callback, [callback...])
`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.verb()` methods are provided to create routes, where **verb** is one of
the HTTP verbs, such as `app.get()` or `app.post()`.
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.
app.get('/', function *(next) {
// ...
});

@@ -55,2 +67,18 @@ Route paths will be translated to regular expressions used to match requests.

Multiple callbacks may be given, and each one will be called sequentially.
app.get(
'/users/:id',
function *(id) {
user = yield User.findOne(id);
return [user];
}, function *(user) {
console.log(user);
// => { id: 17, name: "Alex" }
}
);
You can modify the route parameters for subsequent callbacks by returning an
array of arguments to apply, as shown in the example above.
##### Named parameters

@@ -90,4 +118,17 @@

### Resource routing
### app.redirect(path, destination, [code])
Redirect `path` to `destination` URL with optional 30x status `code`.
app.redirect('/login', 'sign-in');
This is equivalent to:
app.all('/login', function *() {
this.redirect('/sign-in');
this.status = 301;
});
### app.resource(path, actions)
Resource routing is provided by the `app.resource()` method. `app.resource()`

@@ -94,0 +135,0 @@ registers routes for corresponding controller actions, and returns a

/**
* Router tests
* Module tests
*/
var fs = require('fs');
var path = require('path');
var request = require('supertest');
var Router = require('..');
var should = require('should');
var koa = require('koa');
var http = require('http');
var methods = require('methods');
var koa = require('koa')
, should = require('should');
describe('module', function() {
it('should expose Router', function(done) {
var app = koa();
var Router = require('..');
should.exist(Router);

@@ -22,96 +16,1 @@ Router.should.be.a('function');

});
describe('Router', function() {
it('should create new router with koa app', function(done) {
var app = koa();
Router.should.be.a('function');
var router = new Router(app);
router.should.be.instanceOf(Router);
done();
});
it('should expose middleware factory', function(done) {
var app = koa();
var router = new Router(app);
router.should.have.property('middleware');
router.middleware.should.be.a('function');
var middleware = router.middleware();
should.exist(middleware);
middleware.should.be.a('function');
done();
});
it('should match corresponding requests', function(done) {
var app = koa();
app.use(Router(app));
methods.forEach(function(method) {
app.should.have.property(method);
});
app.get('/:category/:title', function *(category, title, next) {
category.should.equal('programming');
title.should.equal('how-to-node');
this.status = 204;
});
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();
});
});
});
it('should support generators', function(done) {
var app = koa();
app.use(Router(app));
app.use(function(next) {
return function *() {
done();
};
});
var readVersion = function() {
return function(fn) {
var packagePath = path.join(__dirname, '..', 'package.json');
fs.readFile(packagePath, 'utf8', function(err, data) {
if (err) return fn(err);
fn(null, JSON.parse(data).version);
});
};
};
app.get('/', function *(next) {
var version = yield readVersion();
this.status = 204;
return yield next;
});
request(http.createServer(app.callback()))
.get('/')
.expect(204)
.end(function(err, res) {
if (err) return done(err);
});
});
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) {
app.routes.should.have.property(method);
app.routes[method].should.include(route);
});
done();
});
});
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