Skip to content
Merged
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
8 changes: 8 additions & 0 deletions src/plugins/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ function createWrapMethod (tracer, config) {
return returned
}

req._datadog_trace_patched = true

return next()
})
}
Expand Down Expand Up @@ -84,6 +86,8 @@ function createWrapProcessParams (tracer, config) {
}

function createWrapRouterMethod (tracer) {
const context = tracer._context

return function wrapRouterMethod (original) {
return function methodWithTrace (fn) {
const offset = this.stack.length
Expand All @@ -94,6 +98,10 @@ function createWrapRouterMethod (tracer) {
const handle = layer.handle_request

layer.handle_request = (req, res, next) => {
if (req._datadog_trace_patched) {
next = context.bind(next)
}

return handle.call(layer, req, res, next)
}

Expand Down
61 changes: 61 additions & 0 deletions test/plugins/express.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,67 @@ describe('Plugin', () => {
})
})

it('should bind the next callback to the current context', done => {
const app = express()

app.use((req, res, next) => {
context.run(() => {
context.set('foo', 'bar')
next()
})
})

app.get('/user', (req, res) => {
res.status(200).send(context.get('foo'))
})

getPort().then(port => {
appListener = app.listen(port, 'localhost', () => {
axios.get(`http://localhost:${port}/user`)
.then(res => {
expect(res.status).to.equal(200)
expect(res.data).to.be.empty
done()
})
.catch(done)
})
})
})

it('should only include paths for routes that matched', done => {
const app = express()
const router = express.Router()

router.use('/baz', (req, res, next) => next())
router.get('/user/:id', (req, res) => {
res.status(200).send()
})
router.use('/qux', (req, res, next) => next())

app.use('/foo', (req, res, next) => next())
app.use('/app', router)
app.use('/bar', (req, res, next) => next())

getPort().then(port => {
agent
.use(traces => {
expect(traces[0][0]).to.have.property('resource', '/app/user/:id')
})
.then(done)
.catch(done)

appListener = app.listen(port, 'localhost', () => {
axios.get(`http://localhost:${port}/app/user/123`)
.then(res => {
expect(res.status).to.equal(200)
expect(res.data).to.be.empty
done()
})
.catch(done)
})
})
})

it('should extract its parent span from the headers', done => {
const app = express()

Expand Down