From 78bf7ee6683ab876e99aba4410380a6b81c3c5a5 Mon Sep 17 00:00:00 2001 From: nicgirault Date: Fri, 29 May 2020 12:06:52 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20add=20ability=20to=20set=20route=20?= =?UTF-8?q?specific=20tags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 16 +++++++++++++--- lib/index.js | 8 +++++--- lib/index.test.js | 17 ++++++++++++++++- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index dfb6486..c574afa 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,19 @@ Datadog middleware for Connect JS / Express Add middleware immediately before your router. - app.use(require("connect-datadog")({})); - app.use(app.router); +```javascript +app.use(require("connect-datadog")({})); +app.use(app.router); +``` + +You can add specific tags in other middlewares: + +```javascript +const someMiddleware = (req, res, next) => { + req.ddTags = ['foo:bar'] + next() +} +``` ## Options @@ -27,4 +38,3 @@ All options are optional. ## License View the [LICENSE](https://github.com/AppPress/node-connect-datadog/blob/master/LICENSE) file. - diff --git a/lib/index.js b/lib/index.js index e5b2699..68df20a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -41,10 +41,12 @@ module.exports = function (options) { let end = res.end; res.end = function (chunk, encoding) { res.end = end; - res.end(chunk, encoding); + res.end(chunk, encoding); + + const routeTags = req.ddTags || []; + + let statTags = [...tags, ...routeTags]; - let statTags = [...tags]; - const route = getRoute(req, base_url); if (route.length > 0) { statTags.push(`route:${route}`); diff --git a/lib/index.test.js b/lib/index.test.js index 11cbb9e..73b2b65 100644 --- a/lib/index.test.js +++ b/lib/index.test.js @@ -38,9 +38,10 @@ describe('connectDatadog', () => { mockStatsDImplementation.increment.mockReset() }) - const asyncConnectDatadogAndCallMiddleware = (options, timeoutInterval = 0) => + const asyncConnectDatadogAndCallMiddleware = (options, timeoutInterval = 0, routeTags = undefined) => new Promise(resolve => { const middleware = connectDatadog(options) + req.ddTags = routeTags middleware(req, res, next) timeoutInterval > 0 @@ -167,6 +168,20 @@ describe('connectDatadog', () => { expectConnectedToDatadog(stat, statTags) }) }) + + describe('when a later middleware add a tag', () => { + it('appends the list of tags to the metric tag', async () => { + const stat = 'node.express.router' + const routeTags = ['foo:bar'] + const statTags = [ + `route:${req.route.path}`, + `response_code:${res.statusCode}`, + ] + + await asyncConnectDatadogAndCallMiddleware({ response_code: true }, 0, routeTags) + expectConnectedToDatadog(stat, [...routeTags, ...statTags]) + }) + }) }) describe('path', () => {