首页 > 解决方案 > Loopback 4 中应该如何实现模型验证?

问题描述

我对 Loopback 4 框架很陌生,我正在尝试将它用于需要连接来自不同类型数据库和服务的数据的小项目。我使用版本 4 的主要原因之一是因为 Typescript,还因为它支持 ES7 功能(async/await),我非常感谢。不过,我不知道如何实现模型验证,至少不像 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);
  }
}

标签: typescriptmodelloopbackv4l2loopback

解决方案


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 存储库中类似问题的回答。


推荐阅读