我正在寻找一种方法来防止不需要的属性出现在 requestBody 中,如关联模型中所述
这是我的模型:
import { Model, model, property } from '@loopback/repository';
@model({
name: 'AwsS3',
strict: true,
description: 'AWS S3 Object description',
properties: {
Key: {
type: 'String',
required: 'true',
},
Bucket: {
type: 'String',
requied: 'true',
},
},
})
export class AwsS3 extends Model {
@property({
type: 'string',
description: 'path/to/file',
required: true,
}) Key: string;
@property({
type: 'string',
description: 'AWS-S3-Bucket-Name',
required: true,
})
Bucket: string;
constructor(data: AwsS3) {
super(data);
}
}
我在 Controller 中这样使用它
function(@requestBody({
required: true,
description: 'aws object settings',
content: {
'application/json': {},
},
}) body : AwsS3
){
console.log(body);
}
当两个属性之一缺失或类型错误时,它会正确抛出。 但是,如果我发送如下所示的 json,则不会抛出任何内容,并且对象会使用 UnwantedProp 进行处理
{
Key: 'key',
Bucket : 'bucket',
UnwantedProp: 40
}
最佳答案
我发现它可以通过使用 @api 装饰器并设置 openapi 规范中的additionalProperties: false 来实现。
像这样使用它:
@api(
basePath: '/',
paths : {
'somepath': {
'post' : {
'x-operation-name': 'myfunction',
'x-controller-name': 'MyController',
// properties for route
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
additionalProperties: false, // <=== here it is
properties: {
Key: { type: 'string'},
Bucket: {type: 'string'},
},
required: ['Bucket', 'Key'],
},
},
},
},
}
}
}
)
export class MyController{
async myfunction(
@requestBody({ settings: { strict: true } }) body
){}
}
测试时它会按预期抛出以下内容:
{
"error": {
"statusCode": 422,
"name": "UnprocessableEntityError",
"message": "The request body is invalid. See error object `details` property for more info.",
"code": "VALIDATION_FAILED",
"details": [
{
"path": "",
"code": "additionalProperties",
"message": "should NOT have additional properties",
"info": {
"additionalProperty": "unwantedProp"
}
}
]
}
}
关于node.js - Loopback 4 如何验证 requestBody 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54289215/