From 5a304a2b425ec2820314efe6d62631076e3be647 Mon Sep 17 00:00:00 2001 From: Nicolas MARTEAU Date: Wed, 18 Sep 2024 11:14:29 +0200 Subject: [PATCH] feat: replace preHandler hook with onRequest to define ip property --- index.js | 2 +- test/index.test.js | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 26b2042..efef4ea 100644 --- a/index.js +++ b/index.js @@ -108,7 +108,7 @@ function fastifyIp ( done() } - instance.addHook('preHandler', redefineIpDecorator) + instance.addHook('onRequest', redefineIpDecorator) } else { instance.decorateRequest('ip', ipDecorator) } diff --git a/test/index.test.js b/test/index.test.js index d865807..dd552bc 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -112,7 +112,7 @@ tap.test('Plugin#Decoration', scope => { }) tap.test('Plugin#Request IP', scope => { - scope.plan(9) + scope.plan(10) scope.test('Should infer the header based on default priority', async t => { const app = fastify() @@ -508,4 +508,26 @@ tap.test('Plugin#Request IP', scope => { } }) }) + + scope.test('Should set the IP in the "onRequest" hook when trustProxy option is set to true', async t => { + const app = fastify({ trustProxy: true }) + const expectedIP = faker.internet.ip() + + app.register(plugin) + app.addHook('onRequest', async (req) => { + t.equal(req.ip, expectedIP) + }) + app.get('/', async (req) => { + t.equal(req.ip, expectedIP) + }) + + t.plan(2) + + await app.inject({ + path: '/', + headers: { + 'x-client-ip': expectedIP + } + }) + }) })