Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit cfd129b

Browse files
committed
feat(request): add support for adding macros
request exposes a macro static method to attach methods to the request prototype
1 parent 43f21a2 commit cfd129b

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/Request/index.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -615,14 +615,25 @@ class Request {
615615
* tells whether or not request has body. It can be
616616
* used by bodyParsers to decide whether or not to parse body
617617
*
618-
* @return {Boolean} [description]
618+
* @return {Boolean}
619619
*
620620
* @public
621621
*/
622622
hasBody () {
623623
return nodeReq.hasBody(this.request)
624624
}
625625

626+
/**
627+
* adds a new method to the request prototype
628+
*
629+
* @param {String} name
630+
* @param {Function} callback
631+
*
632+
* @public
633+
*/
634+
static macro (name, callback) {
635+
this.prototype[name] = callback
636+
}
626637
}
627638

628639
module.exports = Request

test/unit/request.spec.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,4 +1070,20 @@ describe('Request', function () {
10701070
expect(flashMessage[1]).to.equal(querystring.escape('j:'+JSON.stringify(body)))
10711071
})
10721072

1073+
it('should be able to add macro to the request prototype', function () {
1074+
Request.macro('foo', function () {
1075+
return 'foo'
1076+
})
1077+
const request = new Request({}, {}, {get: function () {}})
1078+
expect(request.foo()).to.equal('foo')
1079+
})
1080+
1081+
it('should have access to instance inside the callback', function * () {
1082+
Request.macro('foo', function () {
1083+
return this.request.name
1084+
})
1085+
const request = new Request({name: 'bar'}, {}, {get: function () {}})
1086+
expect(request.foo()).to.equal('bar')
1087+
})
1088+
10731089
})

0 commit comments

Comments
 (0)