Skip to content

Commit 795f84c

Browse files
authoredSep 18, 2024··
feat: replace preHandler hook with onRequest to define ip property (#52)
1 parent ebbca3e commit 795f84c

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed
 

‎index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ function fastifyIp (
108108
done()
109109
}
110110

111-
instance.addHook('preHandler', redefineIpDecorator)
111+
instance.addHook('onRequest', redefineIpDecorator)
112112
} else {
113113
instance.decorateRequest('ip', ipDecorator)
114114
}

‎test/index.test.js

+23-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ tap.test('Plugin#Decoration', scope => {
112112
})
113113

114114
tap.test('Plugin#Request IP', scope => {
115-
scope.plan(9)
115+
scope.plan(10)
116116

117117
scope.test('Should infer the header based on default priority', async t => {
118118
const app = fastify()
@@ -508,4 +508,26 @@ tap.test('Plugin#Request IP', scope => {
508508
}
509509
})
510510
})
511+
512+
scope.test('Should set the IP in the "onRequest" hook when trustProxy option is set to true', async t => {
513+
const app = fastify({ trustProxy: true })
514+
const expectedIP = faker.internet.ip()
515+
516+
app.register(plugin)
517+
app.addHook('onRequest', async (req) => {
518+
t.equal(req.ip, expectedIP)
519+
})
520+
app.get('/', async (req) => {
521+
t.equal(req.ip, expectedIP)
522+
})
523+
524+
t.plan(2)
525+
526+
await app.inject({
527+
path: '/',
528+
headers: {
529+
'x-client-ip': expectedIP
530+
}
531+
})
532+
})
511533
})

0 commit comments

Comments
 (0)
Please sign in to comment.