fastify-type-provider-typebox
fastify-type-provider-typebox copied to clipboard
Is there a way to set additionalProperties to false by default?
Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the feature has not already been requested
🚀 Feature Proposal
schema: {
tags: ["User"],
description: "Endpoint to update user details",
body: Type.Object(
{
firstName: Type.Optional(Type.String({ maxLength: 64 })),
lastName: Type.Optional(Type.String({ maxLength: 64 })),
},
{ additionalProperties: false }// <- make this the default.
),
Make additionalProperties the default and specify in the README that additionalProperties are accepted by default.
Motivation
schema: {
tags: ["User"],
description: "Endpoint to update user details",
body: Type.Object(
{
firstName: Type.Optional(Type.String({ maxLength: 64 })),
lastName: Type.Optional(Type.String({ maxLength: 64 })),
},
{ additionalProperties: false }// <- make this the default.
),
This is an example fastify schema and when you hit this endpoint with:
// Example, just a scenario, does not reflect real use case.
{
"subscription": "premium"
}
For someone who might do a update statement might overlook that a additional keys might be included in the body of the payload unless i set additionalProperties: false
For security reason, or QoL, there should be a setting to set this to the default.
Ajv supports this: https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/
Can we have one for typebox provider?
Example
// Something like this? I might be wrong on this code but this is one way to be implemented. const server = Fastify().setValidatorCompiler((opts) => TypeBoxValidatorCompiler({...opts, additionalProperties: false}))
export const TypeBoxValidatorCompiler: FastifySchemaCompiler<TSchema> = ({ schema, httpPart, additionalProperties }) => {
const typeCheck = TypeCompiler.Compile({...schema, { additionalProperties }})
return (value): any => {
// Note: Only support value conversion for querystring, params and header schematics
const converted = httpPart === 'body' ? value : Value.Convert(schema, value)
if (typeCheck.Check(converted)) {
return { value: converted }
}
const errors = [...typeCheck.Errors(converted)]
return {
// Note: Here we return a FastifySchemaValidationError[] result. As of writing, Fastify
// does not currently export this type. Future revisions should uncomment the assertion
// below and return the full set of properties. The specified properties 'message' and
// 'instancePath' do however result in a near equivalent error messages to Ajv.
error: errors.map((error) => ({
message: ${error.message},
instancePath: error.path
})) // as FastifySchemaValidationError[]
}
}
}