From b374e7f54c4979d248415af6f8be13a9abce7523 Mon Sep 17 00:00:00 2001 From: Konstantin Pogorelov Date: Mon, 28 Nov 2016 11:28:05 +0100 Subject: [PATCH] fix includePath in combination with router --- README.md | 2 +- package.json | 2 +- spec/normalizePathSpec.js | 8 ++++---- src/normalizePath.js | 12 ++++++++++-- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 8ece367..75cfffa 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ app.listen(3000); ## Changelog - * **1.2.0** + * **1.2.1** * upgrade prom-client to 6.1.2 * add options: includeMethod, includePath, keepDefaultMetrics diff --git a/package.json b/package.json index 51ab89f..f13169f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "express-prom-bundle", - "version": "1.2.0", + "version": "1.2.1", "description": "express middleware with popular prometheus metrics in one bundle", "main": "src/index.js", "keywords": [ diff --git a/spec/normalizePathSpec.js b/spec/normalizePathSpec.js index 5e1e6c6..0166cd5 100644 --- a/spec/normalizePathSpec.js +++ b/spec/normalizePathSpec.js @@ -6,23 +6,23 @@ const normalizePath = require("../src/normalizePath"); describe("normalizePath", () => { it("returns original if disabled in opts", () => { expect( - normalizePath({path: "/a/12345"}, {normalizePath: false}) + normalizePath({originalUrl: "/a/12345"}, {normalizePath: false}) ).toBe("/a/12345"); }); it("returns run callback if configured", () => { expect( normalizePath( - {path: "/a/12345"}, + {originalUrl: "/a/12345"}, { - normalizePath: req => req.path + "-ok" + normalizePath: req => req.originalUrl + "-ok" } ) ).toBe("/a/12345-ok"); }); it("uses UrlValueParser by default", () => { - expect(normalizePath({path: "/a/12345"})) + expect(normalizePath({originalUrl: "/a/12345"})) .toBe("/a/#val"); }); }); diff --git a/src/normalizePath.js b/src/normalizePath.js index e27a2a3..e8d5ffc 100644 --- a/src/normalizePath.js +++ b/src/normalizePath.js @@ -1,18 +1,26 @@ "use strict"; const UrlValueParser = require("url-value-parser"); +const url = require("url"); let urlValueParser; module.exports = function(req, opts) { opts = opts || {}; + + // originalUrl is taken, because url and path can be changed + // by middlewares such as "router". Note: this function is called onFinish + /// i.e. always in the tail of the middleware chain + const path = url.parse(req.originalUrl).pathname; + if (opts.normalizePath !== undefined && !opts.normalizePath) { - return req.path; + return path; } if (typeof opts.normalizePath === "function") { return opts.normalizePath(req, opts); } + if (!urlValueParser) { urlValueParser = new UrlValueParser(); } - return urlValueParser.replacePathValues(req.path); + return urlValueParser.replacePathValues(path); };