-
-
Notifications
You must be signed in to change notification settings - Fork 9
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
Unknown request body when using onRequest hook #17
Comments
https://www.fastify.io/docs/latest/Reference/Hooks/#onrequest Checkout the hooks execution order here: https://www.fastify.io/docs/latest/Reference/Lifecycle/#lifecycle |
In this case, the body is also of type unknown when using a preHandler hook. According to https://www.fastify.io/docs/latest/Reference/Lifecycle/#lifecycle, the preHandler hook is called after the validation, so it should be defined right? |
Yes, the body is set on that time |
I stumbled on to the same issue with the preHandler hook. So if I define the schema and use an inline hook, the request body is inferred correctly in the actual handler: server.post(
"/items",
{
schema: {
body: {
type: "object",
properties: {
name: {
type: "string",
},
},
required: ["name"],
} as const,
},
// Inline dummy hook
preHandler: async (request, reply) => {},
},
async (request, reply) => {
// No problems here, request.body.name is a string like it should be
console.log(request.body.name);
}
); However, if I extract the hook into its own function (for reuse purposes and whatnot), then const dummyHook = async (request: FastifyRequest, reply: FastifyReply) => {};
server.post(
"/items",
{
schema: {
body: {
type: "object",
properties: {
name: {
type: "string",
},
},
required: ["name"],
} as const,
},
// Hook is now a dedicated function
preHandler: dummyHook
},
async (request, reply) => {
// TS2571: Object is of type 'unknown'.
console.log(request.body.name);
}
); Is this expected behaviour? Reusing hooks sounds like a common scenario so I might be missing something. One way to work around this is to call the shared hook from the inline hook but it comes off as being a bit redundant: {
schema: {
...
},
preHandler: async (request, reply) => {
await dummyHook(request, reply);
},
},
async (request, reply) => {
// No problems here, request.body.name is a string like it should be
console.log(request.body.name);
} |
I'm also facing issue described in last comment. @Eomm maybe it worth to reopen this for visibility that specifying |
Please re-open. I've been hitting this issue as well and haven't found a feel-good work-around. @mcollina. |
Ran into this issue as well with type information being lost when using a prehandler that is an external method |
Prerequisites
Issue
When using a hook like
onRequest
, the schema validation doesn't work anymore. If e.g. a body schema is specified inMySchema
, the request body will be of typeunknown
:Is this wanted behaviour?
The text was updated successfully, but these errors were encountered: