首页 > 解决方案 > 与请求正文验证一起使用的类型/接口被忽略

问题描述

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

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

标签: node.jstypescriptvalidationloopback

解决方案


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

为了在参数类型中使用@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"
            ]
          }
        }
      }})

推荐阅读