Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: replace preHandler hook with onRequest to define ip property #52

Merged
merged 1 commit into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ function fastifyIp (
done()
}

instance.addHook('preHandler', redefineIpDecorator)
instance.addHook('onRequest', redefineIpDecorator)
} else {
instance.decorateRequest('ip', ipDecorator)
}
Expand Down
24 changes: 23 additions & 1 deletion test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
}
})
})
})
Loading