diff --git a/lib/req.js b/lib/req.js index 85264d0..ff6fb46 100644 --- a/lib/req.js +++ b/lib/req.js @@ -74,8 +74,9 @@ function reqSerializer (req) { _req.query = req.query _req.params = req.params } else { - // req.url.path is for hapi compat. - _req.url = req.path || (req.url ? (req.url.path || req.url) : undefined) + const path = req.path + // path for safe hapi compat. + _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined) } _req.headers = req.headers _req.remoteAddress = connection && connection.remoteAddress diff --git a/test/req.test.js b/test/req.test.js index 4ac9a58..6726e2d 100644 --- a/test/req.test.js +++ b/test/req.test.js @@ -252,6 +252,47 @@ test('req.url will be obtained from input request originalUrl when available', f } }) +test('req.url will be obtained from input request url when req path is a function', function (t) { + t.plan(1) + + const server = http.createServer(handler) + server.unref() + server.listen(0, () => { + http.get(server.address(), () => {}) + }) + + t.teardown(() => server.close()) + + function handler (req, res) { + req.path = function () { + throw new Error('unexpected invocation') + } + req.url = '/test' + const serialized = serializers.reqSerializer(req) + t.equal(serialized.url, '/test') + res.end() + } +}) + +test('req.url being undefined does not throw an error', function (t) { + t.plan(1) + + const server = http.createServer(handler) + server.unref() + server.listen(0, () => { + http.get(server.address(), () => {}) + }) + + t.teardown(() => server.close()) + + function handler (req, res) { + req.url = undefined + const serialized = serializers.reqSerializer(req) + t.equal(serialized.url, undefined) + res.end() + } +}) + test('can wrap request serializers', function (t) { t.plan(3)