在环回4中应如何实施模型验证?

时间:2019-04-20 21:19:13

标签: typescript model loopback v4l2loopback

我对Loopback 4框架还很陌生,我正在尝试将其用于需要连接来自不同数据库和服务的数据的小型项目。我使用版本4的主要原因之一是因为Typescript,还因为它支持ES7功能(异步/等待),对此我非常感谢。尽管如此,我还是不知道如何实现模型验证,至少不像Loopback v3支持那样。

我试图在模型构造函数上实现自定义验证,但是这似乎是一个非常糟糕的模式。

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

@model()
export class Person extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
  })
  id: number;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @property({
    type: 'date',
    required: true,
  })
  birthDate: string;

  @property({
    type: 'number',
    required: true,
  })
  phone: number;

  constructor(data: Partial<Person>) {
    if (data.phone.toString().length > 10) throw new Error('Phone is not a valid number');
    super(data);
  }
}

1 个答案:

答案 0 :(得分:0)

LB4使用ajv模块根据模型元数据验证传入的请求数据。因此,您可以使用jsonSchema如下所述。

export class Person extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
  })
  id: number;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @property({
    type: 'date',
    required: true,
  })
  birthDate: string;

  @property({
    type: 'number',
    required: true,
    jsonSchema: {
      maximum: 10,
    },
  })
  phone: number;

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

希望有效。 有关更多详细信息,请参阅关于LB4存储库here的类似问题的答案。