回送4如何验证requestBody属性

时间:2019-01-21 11:41:07

标签: node.js typescript loopbackjs

我正在寻找一种方法,以防止不想要的属性出现在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);
 }
}

我在控制器中这样使用它

 function(@requestBody({
    required: true,
    description: 'aws object settings',
    content: {
       'application/json': {},
     },
   }) body : AwsS3
 ){
    console.log(body);
 }

当两个属性之一丢失或类型错误时,它将正确抛出。 但是,如果我发送像下面这样的json,则不会抛出任何异常,并且使用UnwantedProp处理对象

{
    Key: 'key',
    Bucket : 'bucket',
    UnwantedProp: 40
}

1 个答案:

答案 0 :(得分:1)

我发现可以通过使用@api装饰器并设置openPro规范中的extraProperties: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"
                }
            }
        ]
    }
}