1个不稳定版本
0.2.0 | 2022年3月12日 |
---|
#361 in #structures
用于 dade
76KB
2K SLoC
dade
dade
是一个用于定义Rust结构数据的框架,类似于Python中的pydantic。
为了轻松处理数据,以下将支持它。
- 对(原始)类型的验证。
- 数值类型;u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
- 布尔值
- 字符串
- 可选
- Vec
- 嵌套模型
- 枚举
- 导出符合JsonSchema的数据模式。
- 从JSON加载模型。
- 从模型导出JSON字符串。
- 实现有用的类型。例如,URL,电子邮件等。
- 发布一个为你实现任何自定义类型及其验证的trait。
请参阅文档以获取更多详细信息。
路线图
实现基本思想。实现(原始)类型,枚举等。- 支持模型配置,例如,将给定的名称设置为JsonSchema中的标题,或排除另一个键。
- 实现有用的类型和自定义类型的trait。
示例
基础
要定义一个模型,您需要以下模块。
use dade::{Model, model};
例如,定义用户模型。
#[model]
struct User {
#[field(ge = 1)]
id: u64,
#[field(min_length = 1, max_length = 100)]
name: String,
#[field(default = "en")]
lang: String,
#[field(min_length = 1, max_length = 255, default = null)]
url: Option<String>,
#[field(default = false)]
verified: bool,
}
然后您可以通过以下方式创建该模型的实例。
let input = "{\"id\": 1, \"name\": \"James Smith\"}";
let user = User::parse(input).unwrap();
然后您可以通过以下方式获取实例的JSON字符串。
let json_string = user.json(false);
// json_string = "{\"id\":1,\"name\":\"James Smith\",\"lang\":\"en\",\"url\":null,\"verified\":false}"
如果您想验证一个值,您可以通过以下方式获取给定模型的符合JsonSchema的模式。
let schema = User::schema();
该模式是
{
"$ref": "#/definitions/User",
"definitions": {
"User": {
"title": "User",
"type": "object",
"properties": {
"id": {
"type": "integer",
"title": "Id",
"minimum": 1
},
"name": {
"type": "string",
"title": "Name",
"minLength": 1,
"maxLength": 100
},
"lang": {
"type": "string",
"title": "Lang",
"default": "en"
},
"url": {
"type": "string",
"title": "Url",
"default": null,
"minLength": 1,
"maxLength": 255
},
"verified": {
"type": "boolean",
"title": "Verified",
"default": false
}
},
"required": ["id", "name"]
}
}
}
高级
- 如果您想绑定其他名称
#[model]
struct User {
id: u64,
#[field(alias = "FirstName")]
first_name: String,
#[field(alias = "LastName")]
last_name: String,
}
- 如果您需要一个嵌套模型
#[model]
struct Name {
first_name: String,
last_name: String,
}
#[model]
struct User {
id: u64,
name: Name,
}
- 如果您需要一个自引用模型
#[model]
struct Item {
id: u64,
name: String,
value: u128,
related_items: Option<Vec<Box<Item>>>,
}
依赖项
~1.5MB
~35K SLoC