fastify/help

Access request data from inside JSON schema or keyword validator

purplepenguin2 opened this issue · 3 comments

💬 Question here

I'd like to use data from an earlier hook as part of the schema for a later route. Is this possible to do? For example:

fastify.post(
  '/',
  {
    schema: {
      body: {
        type: 'object',
        properties: {
          myCoolProp: { enum: req.arrayValueFromEarlierHook },
        },
        required: ['myCoolProp'],
      },
    },
  },
  async (req, res) => {
    // bleh
  },
);

I know I could also do the validation manually in the route handler itself, but it'd be nice to get the built-in error messaging, etc. by using a schema. I realize it's not possible to simply declare it the way I did in the example above since they're compiled on server start, but the example is just to get the use case across. I was looking at adding a custom keyword as well, but it doesn't appear the keyword validate function has access to the request object either. Is there a straightforward way to achieve this, or is this simply not possible?

Your Environment

  • node version: latest
  • fastify version: latest
  • os: Mac and Linux

It's possible but it'd be complex and non performant, as well as probably unsafe.

Yeah, I figured it would take a performance hit, and the input is coming from a validated source, so it's not random from a user, but fair enough. I didn't think it would be simple, but wanted to triple check I wasn't missing anything obvious. To close this out, I'm assuming your recommendation would simply be to do the check in the route itself and not as part of the schema? Thanks.

EDIT: Is there a simple way to still get the same validation error behavior from default Fastify, or is that more messy/complicated than it's worth as well? I imagine something like request.validateInput but have it actually throw the same formatted 400 error with message? Didn't know if there was a built-in way, other than just manually using ajv?

You can use request.validateInput to re-use the route schema, but that won't give you the same error behaviour, just reuse the schema for validation; it will be up to the implementer how to handle the bad input