Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make it work with Async Hooks #404

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ unreleased
- deps: [email protected]
* deps: [email protected]
* deps: type-is@~1.6.18
* Make it work with Async Hooks

1.19.0 / 2019-04-25
===================
Expand Down
69 changes: 49 additions & 20 deletions lib/read.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,30 +73,35 @@ function read (req, res, next, parse, debug, options) {
}

// read body
debug('read body')
getBody(stream, opts, function (error, body) {
if (error) {
var _error

if (error.type === 'encoding.unsupported') {
// echo back charset
_error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase(),
type: 'charset.unsupported'
})
} else {
// set status code on error
_error = createError(400, error)
}
function readErrorHandler (error) {
var _error
if (error.type === 'encoding.unsupported') {
// echo back charset
_error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase(),
type: 'charset.unsupported'
})
} else {
// set status code on error
_error = createError(400, error)
}

// read off entire request
stream.resume()
onFinished(req, function onfinished () {
// read off entire request
stream.resume()
if (isPromiseAvailable()) {
new Promise(function (resolve) {
onFinished(req, resolve)
}).then(function () {
next(createError(400, _error))
})
} else {
onFinished(req, function () {
next(createError(400, _error))
})
return
}
}

function readSuccessHandler (body) {
// verify
if (verify) {
try {
Expand Down Expand Up @@ -128,7 +133,20 @@ function read (req, res, next, parse, debug, options) {
}

next()
})
}

debug('read body')
if (isPromiseAvailable()) {
getBody(stream, opts)
.then(readSuccessHandler, readErrorHandler)
} else {
getBody(stream, opts, function (error, body) {
if (error) {
return readErrorHandler(error)
}
readSuccessHandler(body)
})
}
}

/**
Expand Down Expand Up @@ -179,3 +197,14 @@ function contentstream (req, debug, inflate) {

return stream
}

/**
* Check whether Promise is available.
*
* @return {boolean}
* @private
*/

function isPromiseAvailable () {
return typeof global.Promise === 'function'
}
58 changes: 58 additions & 0 deletions test/body-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ var http = require('http')
var methods = require('methods')
var request = require('supertest')

var describeWhenAsyncHooksAreSupported = describe.skip
try {
var asyncHooks = require('async_hooks')
describeWhenAsyncHooksAreSupported = typeof asyncHooks.AsyncLocalStorage === 'function' ? describe : describe.skip
} catch (ignored) {
}

var bodyParser = require('..')

describe('bodyParser()', function () {
Expand Down Expand Up @@ -51,6 +58,57 @@ describe('bodyParser()', function () {
.expect(200, '{"user":"tobi"}', done)
})

describeWhenAsyncHooksAreSupported('used with async hooks', function () {
it('should maintain context when parsing was successful', function (done) {
var _bodyParser = bodyParser()
var asyncLocalStorage = new asyncHooks.AsyncLocalStorage()

var server = http.createServer(function (req, res) {
const store = {
contextMaintained: true
}
asyncLocalStorage.run(store, function () {
_bodyParser(req, res, function (err) {
res.statusCode = err ? (err.status || 500) : 200
res.end(err ? err.message : JSON.stringify(asyncLocalStorage.getStore()))
})
})
})

request(server)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":"tobi"}')
.expect(200, '{"contextMaintained":true}', done)
})

it('should maintain context when parsing has failed', function (done) {
var _bodyParser = bodyParser.text()
var asyncLocalStorage = new asyncHooks.AsyncLocalStorage()

var server = http.createServer(function (req, res) {
const store = {
contextMaintained: true
}
asyncLocalStorage.run(store, function () {
_bodyParser(req, res, function (err) {
if (!err) {
res.statusCode = 500
res.end('parsing was expeced to fail, but it succeeded')
}
res.end(JSON.stringify(asyncLocalStorage.getStore()))
})
})
})

request(server)
.post('/')
.set('Content-Type', 'text/plain; charset=x-fake')
.send('user is tobi')
.expect(200, '{"contextMaintained":true}', done)
})
})

describe('http methods', function () {
before(function () {
var _bodyParser = bodyParser()
Expand Down