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.0.1 to 1.1.1

resource.js

49

index.js

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

var Route = require('./route');
var Resource = require('./resource');
var parse = require('url').parse;

@@ -38,10 +39,20 @@

methods.forEach(function(method) {
app[method] = function(pattern, callback) {
app.map([method.toUpperCase()], pattern, callback);
app[method] = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift([method.toUpperCase()]);
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;
};
};
/**
* Router middleware. Dispatches route callback corresponding to the request.
* Router middleware. Dispatches route callbacks corresponding to the request.
*

@@ -59,12 +70,23 @@ * @param {Application} app

return function *() {
// Find matching route and dispatch it
// Find matching route
var route;
var routes = app.routes[this.req.method];
for (var len = routes.length, i=0; i<len; i++) {
var route = routes[i];
if (route.match(this.req.method, parse(this.req.url).path)) {
app.context({params: route.params});
return yield route.callback.apply(this, route.paramsArray.concat([next]));
if (routes[i].match(this.req.method, parse(this.req.url).path)) {
route = routes[i];
}
}
yield next;
// Dispatch route callbacks
if (route) {
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;
}
};

@@ -108,3 +130,3 @@ };

* @param {String} pattern
* @param {Function} callback
* @param {Function} callbacks
* @return {Route}

@@ -114,4 +136,7 @@ * @api public

router.route = function(methods, pattern, callback) {
var route = new Route(methods, pattern, callback);
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++) {

@@ -118,0 +143,0 @@ this.routes[methods[i]].push(route);

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

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

@@ -15,2 +15,3 @@ "dependencies": {

"koa": "0.0.1",
"lingo": "0.0.5",
"methods": "0.0.1"

@@ -17,0 +18,0 @@ },

# Router middleware for [koa](https://github.com/koajs/koa)
RESTful resource routing for [koa](https://github.com/koajs/koa).
* REST routing using `app.get`, `app.post`, etc.
* Rails-like resource routing, with nested resources.
* Named parameters.
* Multiple route callbacks.

@@ -35,3 +38,6 @@ ## Install

app.get('/:category/:title', function *(category, title, next) {
console.log(this.params); // Also available in app context
console.log(this.params);
// { category: 'programming', title: 'How to Node' }
console.log(this.paramsArray);
// [ 'category', 'title' ]
});

@@ -47,2 +53,73 @@

### Resource routing
Resource routing is provided by the `app.resource()` method. `app.resource()`
registers routes for corresponding controller actions, and returns a
`Resource` object that can be used to further nest resources.
var app = require('koa')()
, router = require('koa-router')(app);
app.use(router);
app.resource('users', require('./user'));
#### Action mapping
Actions are then mapped accordingly:
GET /users -> index
GET /users/new -> new
POST /users -> create
GET /users/:user -> show
GET /users/:user/edit -> edit
PUT /users/:user -> update
DELETE /users/:user -> destroy
#### Top-level resource
Omit the resource name to specify a top-level resource:
app.resource(require('./frontpage'));
Top-level controller actions are mapped as follows:
GET / -> index
GET /new -> new
POST / -> create
GET /:id -> show
GET /:id/edit -> edit
PUT /:id -> update
DELETE /:id -> destroy
#### Auto-loading
Automatically load requested resources by specifying the `load` action
on your controller:
var actions = {
show: function *(user) {
this.body = user;
},
load: function *(id) {
return users[id];
}
};
app.resource('users', actions);
The `user` object will then be available to the relevant controller actions.
You can also pass the load method as an option:
app.resource('users', require('./users'), { load: User.findOne });
#### Nesting
Resources can be nested using `resource.add()`:
var forums = app.resource('forums', require('./forum'), { load: Forum.findOne });
var theads = app.resource('threads', require('./threads'), { load: Thread.findOne });
forums.add(threads);
## Tests

@@ -49,0 +126,0 @@

/**
* Create new Route with given `methods`, `pattern`, and `callback`.
* Initialize a new Route with given `methods`, `pattern`, and `callbacks`.
*
* @param {String} method
* @param {String} pattern
* @param {Function} callback
* @param {Function} callbacks
* @return {Route}

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

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

@@ -49,3 +50,3 @@

var matches = path.match(this.regexp);
if (matches && matches.length > 1) {
if (matches && matches.length > 0) {
this.paramsArray = matches.slice(1);

@@ -64,17 +65,2 @@ }

/**
* Convert given `pattern` to regular expression.
*
* @param {String} pattern
* @return {RegExp}
* @api private
*/
function patternToRegExp(pattern) {
pattern = pattern
.replace(/\//g, '\\/')
.replace(/:\w+/g, '([^\/]+)');
return new RegExp('^' + pattern + '$', 'i');
};
/**
* Extract parameter names from given `pattern`

@@ -87,6 +73,6 @@ *

function patternToParamNames(pattern) {
Route.patternToParamNames = function(pattern) {
var params = [];
var matches = pattern.match(/(:\w+)/g);
if (matches && matches.length > 1) {
if (matches && matches.length > 0) {
for (var len = matches.length, i=0; i<len; i++) {

@@ -98,1 +84,17 @@ params.push(matches[i].substr(1));

};
/**
* Convert given `pattern` to regular expression.
*
* @param {String} pattern
* @return {RegExp}
* @api private
*/
Route.patternToRegExp = function(pattern) {
pattern = pattern
.replace(/\//g, '\\/') // Escape slashes.
.replace(/:\w+/g, '([^\/]+)') // Replace patterns with capture groups.
.replace(/^(.+)\/$/, '$1\/?'); // Make trailing slashes optional.
return new RegExp('^' + pattern + '$', 'i');
};
/**
* Router test
* Router tests
*/

@@ -4,0 +4,0 @@

/**
* Route test
* Route tests
*/

@@ -52,2 +52,23 @@

});
it('should support multiple callbacks', function(done) {
var app = koa();
app.use(router(app));
app.get(
'/:category/:title',
function *(category, title) {
this.status = 500;
},
function *(category, title) {
this.status = 204
}
);
request(http.createServer(app.callback()))
.get('/match/this')
.expect(204)
.end(function(err) {
if (err) return done(err);
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