与请求正文验证一起使用的类型/接口将被忽略

问题描述 投票:0回答:1

给定控制器内定义的以下接口:

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 }

如果你想测试这个问题,请检查this repo

node.js typescript validation loopback
1个回答
0
投票

根据documentation,您需要将相应的模型装饰器添加到您的模型中:

为了在参数类型中使用@requestBody,参数类型中的模型必须使用@model和@property进行修饰。

所以你可以这样做:

@model()
class idAndAge {
  @property({ required: true })
  id: string;
  @property({ required: true })
  age: number
}

和loopback将根据生成的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"
            ]
          }
        }
      }})
© www.soinside.com 2019 - 2024. All rights reserved.