如何在Loopback 4中实现模型验证?

问题描述 投票:0回答:1

我是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);
  }
}

typescript model loopback v4l2loopback
1个回答
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 repo here的类似问题的答案。

© www.soinside.com 2019 - 2024. All rights reserved.