diff --git a/README.md b/README.md
index 570f784..3bd63ca 100644
--- a/README.md
+++ b/README.md
@@ -42,6 +42,26 @@ function _runMiddlewares (err, req, res) {
// => routing function
}
```
+
+#### Keep the context
+If you need it you can also keep the context of the calling function by calling `run` with `run(req, res, this)`, in this way you can avoid closures allocation.
+
+```js
+http
+ .createServer(function handler (req, res) {
+ middie.run(req, res, { context: 'object' })
+ })
+ .listen(3000)
+
+function _runMiddlewares (err, req, res, ctx) {
+ if (err) {
+ console.log(err)
+ res.end(err)
+ return
+ }
+ console.log(ctx)
+}
+```
#### Restrict middleware execution to a certain path(s)
diff --git a/middie.js b/middie.js
index 29c75f8..b112ac1 100644
--- a/middie.js
+++ b/middie.js
@@ -24,9 +24,9 @@ function middie (complete) {
return this
}
- function run (req, res) {
+ function run (req, res, ctx) {
if (!middlewares.length) {
- complete(null, req, res)
+ complete(null, req, res, ctx)
return
}
@@ -34,6 +34,7 @@ function middie (complete) {
holder.req = req
holder.res = res
holder.url = sanitizeUrl(req.url)
+ holder.context = ctx
holder.done()
}
@@ -42,6 +43,7 @@ function middie (complete) {
this.req = null
this.res = null
this.url = null
+ this.context = null
this.i = 0
var that = this
@@ -49,12 +51,14 @@ function middie (complete) {
const req = that.req
const res = that.res
const url = that.url
+ const context = that.context
const i = that.i++
if (err || middlewares.length === i) {
- complete(err, req, res)
+ complete(err, req, res, context)
that.req = null
that.res = null
+ that.context = null
that.i = 0
pool.release(that)
} else {
diff --git a/test.js b/test.js
index 3291980..ee730bf 100644
--- a/test.js
+++ b/test.js
@@ -205,3 +205,25 @@ test('Should strip the url to only match the pathname', t => {
instance.run(req, res)
})
+
+test('should keep the context', t => {
+ t.plan(6)
+
+ const instance = middie(function (err, a, b, ctx) {
+ t.error(err)
+ t.equal(a, req)
+ t.equal(b, res)
+ t.ok(ctx.key)
+ })
+ const req = {
+ url: '/test'
+ }
+ const res = {}
+
+ t.equal(instance.use(function (req, res, next) {
+ t.pass('function called')
+ next()
+ }), instance)
+
+ instance.run(req, res, { key: true })
+})