fastify / website

https://fastify.dev/
MIT License
60 stars 63 forks source link

Comment on `removeAdditional` is unclear #140

Closed G0maa closed 1 year ago

G0maa commented 1 year ago

Prerequisites

Issue

Hello,

In this Docs link I believe that the // remove additional properties comment is kind of unclear, meaning: when I read it I assumed that by default any additional properties would get removed automatically, which isn't the case.

Additional properties get removed only when their JSON Schema has additionalProperties: false, see this issue.

My suggestions is to simply change the comment to mention this small but important detail.

There's other places where removeAdditional is mentioned like here.

Uzlopak commented 1 year ago

Please provide a PR :)

G0maa commented 1 year ago

Please provide a PR :)

Will do, here's a quick reproducible example... since I spent too much time researching this.

import Fastify from 'fastify';
const fastify = Fastify({
  logger: true,
});

// How to remove additional properties using JSON Schema in Fastify,
// also works with TypeBuilders e.g. TypeBox.
// try with:
// curl -X POST -H "Content-Type: application/json" -d '{"name":"G0maa", "extra": "will exist"}' http://localhost:3000/extraExists
// and:
// curl -X POST -H "Content-Type: application/json" -d '{"name":"G0maa", "extra": "Will not exist"}' http://localhost:3000/noExtra

const schema = {
  body: {
    type: 'object',
    properties: {
      name: { type: 'string' },
    },
  },
};

fastify.post('/extraExists', { schema }, function (request, reply) {
  console.log('Request Body: ', request.body);
  reply.send(request.body);
});

// `additionalProperties: false` has to be set explicitly.
const schemaR = {
  body: {
    type: 'object',
    properties: {
      name: { type: 'string' },
    },
    additionalProperties: false,
  },
};

fastify.post('/noExtra', { schema: schemaR }, function (request, reply) {
  console.log('Request Body: ', request.body);
  reply.send(request.body);
});

fastify.listen({ port: 3000 }, function (err, address) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});
mcollina commented 1 year ago

I think the best way to fix this is to add a link to Ajv documentation: https://ajv.js.org/guide/modifying-data.html#removing-additional-properties.

G0maa commented 1 year ago

I created a PR here.

G0maa commented 1 year ago

Closing since https://github.com/fastify/fastify/pull/4948 got merged.