如何从查询中删除非模式参数



根据fasttify 4.0文档,Ajv的默认选项包括removeAdditional: true。我有一个queryString模式,当我发送一个带有不存在于该模式中的参数的查询时,我希望该参数被删除。但是没有这样的事情发生。模式本身非常普通

querystring: {
type: "object",
properties: { … }
}

我的一些参数是类型数组,也有我希望任何额外的值(通过enum指定的那些之外被删除。我怎样才能做到这一点呢?

更新:我将在下面添加实际的模式(为简洁起见,删除了一些信息)

{
'$schema': 'https://json-schema.org/draft/2020-12/schema',
'$id': 'https://example.com/treatments.schema.json',
title: 'Treatments',
summary: 'Fetches treatments',
description: 'Treatments are…',
response: {},
querystring: {
type: 'object',
additionalProperties: false,
properties: {
treatmentId: {
type: "string",
maxLength: 32,
minLength: 32,
description: "A 32 character string: treatmentId=388D179E0D564775C3925A5B93C1C407"
},
… <snipped> …
}
},
tags: [ 'zenodeo' ]
}

我知道模式正在被验证,因为http://localhost:3010/v3/treatments?treatmentId=foo给出了错误{"statusCode":400,"error":"Bad Request","message":"querystring/treatmentId must NOT have fewer than 32 characters"}(这是好的👍🏽),但additionalProperties: false约束仍然不起作用,因为http://localhost:3010/v3/treatments?foo=bar没有给出错误,foo也没有从request.query中删除(这是不好的👎🏽)

对于removeAdditional: true,您仍然必须在模式上设置additionalProperties: false:

querystring: {
type: "object",
properties: { … },
additionalProperties: false
}

看到https://ajv.js.org/json-schema.html additionalproperties

您还可以更改默认行为removeAdditional: 'all'在这种情况下,你不必设置additionalProperties: false模式。

查看页面的中间部分:https://www.fastify.io/docs/latest/Reference/Validation-and-Serialization/

最新更新