fastify/website

Comment on `removeAdditional` is unclear

G0maa opened this issue · 5 comments

G0maa commented

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

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.

Please provide a PR :)

G0maa commented

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);
  }
});

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

I created a PR here.

G0maa commented

Closing since fastify/fastify#4948 got merged.