1 个不稳定版本
0.1.4 | 2022 年 2 月 23 日 |
---|---|
0.1.3 |
|
0.1.2 |
|
0.1.1 |
|
0.1.0 |
|
在 #序列化 中排名 #1560
40KB
1K SLoC
dade
dade 是 Rust 结构体的数据定义。
为了轻松处理数据,以下将支持它。
- 数据验证。
- 数据模式符合 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>>>,
}
依赖项
~1.5MB
~35K SLoC