Skip to content
Open
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
7 changes: 7 additions & 0 deletions lib/make-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ function drainStream (stream) {

function makeMiddleware (setup) {
return function multerMiddleware (req, res, next) {
// If we are in a node environment that supports async_hooks, preserve
// the current async context.
try {
var asyncHooks = require('node:async_hooks')
next = asyncHooks.AsyncResource.bind(next)
} catch (_) {}

if (!is(req, ['multipart'])) return next()

var options = setup()
Expand Down
23 changes: 23 additions & 0 deletions test/functionality.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,27 @@ describe('Functionality', function () {
done()
})
})

it('should preserve async_hooks context', function (done) {
makeStandardEnv(function (err, env) {
if (err) return done(err)

var parser = env.upload.single('small0')
env.form.append('small0', util.file('small0.dat'))

try {
var asyncHooks = require('node:async_hooks')
var asyncLocalStorage = new asyncHooks.AsyncLocalStorage()
asyncLocalStorage.run('foo', function () {
util.submitForm(parser, env.form, function (err, req) {
assert.ifError(err)
assert.strictEqual(asyncLocalStorage.getStore(), 'foo')
done()
})
})
} catch (_) {
// don't test async_hooks functionality in environments that don't support it
}
})
})
})