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

fix: Preserve async hooks context in supported environments #1124

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/make-middleware.js
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
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
}
})
})
})