node.js - 与请求正文验证一起使用的类型/接口被忽略
问题描述
给定控制器内部定义的以下接口:
interface idAndAge {
id : string,
age : number
}
这是端点定义:
@put('/tests')
async replaceById(
@requestBody() test: idAndAge,// <--to validate the input
): Promise<void> {
await this.testRepository.updateAll(test,{id : test.id});
}
例如,当此端点接收到以下输入时(具有未在接口中定义的属性):
{ anyKey: anyValue }
它接受它并忽略验证
它不应该允许以下值 - 因为它们不包括/反对我们的接口 idAndAge
{ anyKey: anyValue }
如果你想测试这个问题,请检查这个 repo
解决方案
根据文档,您需要将相应的模型装饰器添加到您的模型中:
为了在参数类型中使用@requestBody,参数类型中的模型必须用@model 和@property 修饰。
所以你可以简单地做:
@model()
class idAndAge {
@property({ required: true })
id: string;
@property({ required: true })
age: number
}
并且环回将根据生成的 json-schema 正确验证请求正文。
更新:Afaik 目前不支持添加“allowAdditionalProperties”装饰器,但您可以直接在 requestBody-decorator 中使用 json-schema,如下所示:
@requestBody({
required: true,
content: {
'application/json': {
schema: {
type: 'object',
additionalProperties: false, // <=== important
properties: {
id: { type: 'string' },
age: { type: 'number' }
},
required: [
"id"
]
}
}
}})
推荐阅读
- mysql - 更新 <\DATE> 作为 MSAccess 和 MySQL 保存中字符串的一部分
- typescript - 使用 TypeScript 会使 apk 大小变大?
- css - 如何使css具有每行始终具有相同高度的反应列
- php - 如何通过laravel中的api对Web登录页面进行身份验证
- angular - 为什么 IdentityServer 4 代码流在一段时间后得到 invalid_grant 响应?
- android - android 10中的后台服务每10分钟获取一次位置
- flutter - 颤振将日期时间转换为字符串在午夜失败
- android - Textstyle 在发布时没有唤醒
- string - 如何使用 Flutter TextFormField 在行开头和结尾进行缩进和缩进
- html - 为什么我的图标没有显示在 HTML 网站中?