2个不稳定版本
0.2.0 | 2022年3月12日 |
---|---|
0.1.4 | 2022年2月23日 |
#888 在 数据结构
755KB
1.5K 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、电子邮件等。
- 发布一个用于实现任何自定义类型及其验证的特质。
有关更多详细信息,请参阅文档。
路线图
实现基本想法。实现(原始)类型、枚举等。- 支持模型的配置,例如,将JsonSchema中的给定名称设置为标题,或排除另一个键。
- 实现有用类型和自定义类型的特质。
示例
基础
要定义模型,您需要以下模块。
use dade::{Model, model};
例如,定义user-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>>>,
}