Add the ability to pass arguments to the route handler at route time

Arguments passed in to the route method at route time will be passed in
to the handler for that route.

var router = new Router()
router.add('/some/path' function (someParam) {
    // someParam would be 123
})
router.route('/some/path', {args: [123]})
master
Buddy Sandidge 9 years ago
parent 2fbcab6dd2
commit 2784f9d492

@ -73,4 +73,11 @@ router.route('/by/func/123')
router.route('/unknown/route', function (err) {
// Router.isNotFound(err) === true
})
// Can pass arguments to route handler
router.add(['/with/args', toInt], function (someObj, param) {
// someObj = {some: 'obj'}
// param === 123
})
router.route('/with/args/123', {args: [{some: 'obj'}]})
```

@ -20,10 +20,16 @@ assign(Router.prototype, {
return this.routes.add(this._uriToParts(path), handler)
},
route: function route(path, done) {
route: function route(path, options, done) {
if (done == null && isFunction(options)) {
done = options
options = {}
}
options = options || {}
var routeArray = this._uriToParts(path)
done = done || noop
return this.routes.get(routeArray, [], function (err, func, context, args) {
function _routeCallback(err, func, context, args) {
if (err) {
return done(err)
} else {
@ -33,7 +39,9 @@ assign(Router.prototype, {
return done(new NotFoundError('not found', {location: path}))
}
}
})
}
return this.routes.get(routeArray, (options.args || []), _routeCallback)
},
_uriToParts: function _uriToParts(uri) {

@ -1,6 +1,6 @@
{
"name": "routing-buddy",
"version": "0.1.2",
"version": "0.2.0",
"description": "Another router library for both client and server",
"main": "lib/router.js",
"scripts": {

@ -78,5 +78,14 @@ module.exports = describe('RouteNode', function () {
})
})
it('→ pass arguments to handler before parsing', function (done) {
var obj = {}
node.add(['id', /\d+/], callback)
node.get(['id', '123'], [obj], function (err, cb, ctx, args) {
expect(args).toEqual([obj, '123'])
done()
})
})
})
})

@ -86,6 +86,18 @@ describe('Router', function () {
})
})
it('→ pass in arguments before capturing path arguments', function (done) {
var router = new Router()
var api = {key: 123, any: 'object is passed', method: function () {}}
router.add(['/by/order', /(\d+)/], function (inputApi, urlParam) {
expect(inputApi).toBe(api)
expect(urlParam).toBe('123')
done()
})
router.route('/by/order/123', {args: [api]})
})
it('→ get based on function', function (done) {
function toInt(part) {
var results = /^(\d+)$/.exec(part)
@ -102,7 +114,7 @@ describe('Router', function () {
})
router.route('/by/order/123', function (err) {
expect(err).toBe(null, err && err.message)
expect(err).toBe(null)
done()
})
})

Loading…
Cancel
Save