如何使用Loopback4中的模型验证嵌套的JSON API请求主体有效负载?

时间:2019-06-26 18:53:15

标签: node.js json typescript api

我正在尝试使用loopback4中的模型来验证嵌套的JSON有效负载。 Loopback4能够验证名称和描述属性。但是,它无法验证contact.type或contact.number属性。

这是我的模型的示例:

联系方式:

import {Model, model, property} from '@loopback/repository';

@model({settings: {}})
export class Contact extends Model {
  @property({
    type: 'string',
    required: true,
    default: 'phone',
  })
  type: string;

  @property({
    type: 'number',
    default: 999999999,
  })
  number?: number;


  constructor(data?: Partial<Contact>) {
    super(data);
  }
}

用户模型:

import {Entity, model, property} from '@loopback/repository';
import {Contact} from './contact.model';

@model({settings: {}})
export class User extends Entity {
  @property({
    type: 'string',
    id: true,
    required: true,
  })
  name: string;

  @property({
    type: 'string',
  })
  description?: string;

  @property({
    type: 'object',
    required: true,
  })
  contact: Contact;

  constructor(data?: Partial<User>) {
    super(data);
  }
}

这是我的有效载荷请求主体的样子:

{
    "name": "user1",
    "description": "random user",
    "contact": {
        "type": "phone",
        "number" : 999999999
    }
}

当前行为:当我从请求正文有效负载中删除名称时,它引发错误,提示缺少必需的参数。但是,当我从有效载荷中删除contact.type参数时,它不会引发相同的错误。

预期的行为:Loopback4应该引发错误,表明缺少必需的参数contact.type。

0 个答案:

没有答案