typescript - 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);
}
}
解决方案
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 存储库中类似问题的回答。
推荐阅读
- python - 如何将两个变量中的数据写入文件python
- javascript - 用状态 rgb 反应设置背景颜色
- mysql - 插入语句上的多项选择 - mySQL
- android - 如何从 Firebase 动态链接中检索短 url 链接
- reactjs - 如何使用 react-native-maps 启用倾斜?
- holoviews - 修改 holoviews sankey graph 的样式选项
- react-native - React 原生闪屏本地化
- php - Limit and offset do not work for pagination in Codeigniter3
- python - 在Python中一次增加一个计数器而不使用更新
- synchronization - Vulkan 中统一缓冲区的最佳实践