Skip to content

Commit

Permalink
Merge pull request #9 from fastify/keep-this-context
Browse files Browse the repository at this point in the history
Keep this context
  • Loading branch information
delvedor authored Aug 24, 2017
2 parents ae539cb + 456c739 commit 851d34b
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 3 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ function _runMiddlewares (err, req, res) {
// => routing function
}
```
<a name="keep-context"></a>
#### 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)
}
```

<a name="restrict-usage"></a>
#### Restrict middleware execution to a certain path(s)
Expand Down
10 changes: 7 additions & 3 deletions middie.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,17 @@ 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
}

const holder = pool.get()
holder.req = req
holder.res = res
holder.url = sanitizeUrl(req.url)
holder.context = ctx
holder.done()
}

Expand All @@ -42,19 +43,22 @@ function middie (complete) {
this.req = null
this.res = null
this.url = null
this.context = null
this.i = 0

var that = this
this.done = function (err) {
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 {
Expand Down
22 changes: 22 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
})

0 comments on commit 851d34b

Please sign in to comment.