fastify / fastify-response-validation

A simple plugin that enables response validation for Fastify.
MIT License
51 stars 14 forks source link

Support shortcut schema syntax #35

Closed SleepWalker closed 3 years ago

SleepWalker commented 3 years ago

🚀 Feature Proposal

It is possible to drop wrapping object with type/properties keys and pass a properties directly (see 201 response schema):

image

https://www.fastify.io/docs/latest/Validation-and-Serialization/#serialization

Unfortunately fastify-response-validation won't pickup such syntax. onRoute is called before fastify will normalize schema definition therefore buildHook will be called with unexpected data: https://github.com/fastify/fastify-response-validation/blob/master/index.js#L22-L23

Example

test('Should support shortcut schema syntax', async t => {
  const fastify = Fastify()
  fastify.register(plugin)

  fastify.route({
    method: 'GET',
    path: '/',
    schema: {
      response: {
        '2xx': {
          answer: { type: 'number' }
        }
      }
    },
    handler: async (req, reply) => {
      return { answer: '42' }
    }
  })

  const response = await fastify.inject({
    method: 'GET',
    path: '/'
  })

  t.is(response.statusCode, 500)
  t.deepEqual(JSON.parse(response.payload), {
    statusCode: 500,
    error: 'Internal Server Error',
    message: 'response.answer should be number'
  })
})
climba03003 commented 3 years ago

I personally do not think it is a good idea to implement the shortcut, because it create a bunch of problem when other plugins need to make use of the input schema. e.g. fastify-swagger.

But, free feel to send an PR for the feature you want. Remember to add an unit test.

SleepWalker commented 3 years ago

This shortcut is officially documented way to declare schemas so I think any plugin should actually support this format

mcollina commented 3 years ago

Would you like to send a Pull Request to address this issue? Remember to add unit tests.