是QUEEN的一部分?
**使用自己的蓝图验证 JSON ??**
动机
我们在工作中几乎每天都使用 JSON,有了空安全,我们可以跳过许多错误,但我们无法测试 API 在每次更新后是否仍然完整,
并且更新不会破坏任何数据类型或模式。
所以我们制作了这个包,你可以在测试你用 Dart 消费的 API 或你用 Dart 构建的 API 时使用它。
如果你对 palace 项目的服务器端 Dart 感兴趣,我们可以提供一些帮助。
希望你今天用这个包度过一个无 bug 的时光?
注意
此包依赖于 Dart >= 2.13.0 如果你想在 Flutter 中使用它
你必须更新到 flutter >= 2.5
功能
- 验证 JSON 以匹配你想要的任何模式?
- 支持 Dart 原生类型?
- 支持 TypeOrNull
- 支持
.of进行更深层次的验证? - 抛出错误或返回 false 作为结果?
- 强类型,同时蓝图只是一个 map,但值必须是
BluePrintField的子类型,它包含所有支持的类型,无论是可空还是不可空。 - 告诉你哪个键是失败的以及为什么?
- 已测试?
支持的类型
| 数据类型 | 非可空字段 | 可空字段 |
|---|---|---|
| 字符串 | StringF | StringOrNull |
| 整数 | IntF | IntOrNull |
| 双精度 | DoubleF | DoubleOrNull |
| num | NumF | NumOrNull |
| 布尔值 | BoolF | BoolOrNull |
| 地图 | MapF | MapOrNull |
| 列表 | ListF | ListOrNull |
注意事项
1 – 使用 matchMap 或 matchF 获取 true 或 false 作为结果
2 – 将 throwable 参数设置为 true,以便在不匹配时抛出错误
3 – 在 Map 和 List 上使用 .of() 函数,它在四条规则 MapF、MapOrNull、ListF、ListOrNull 上可用,以便更深入地验证对象。
4 – 对于空值,可空字段规则将不会根据参数进行验证,并将其视为匹配
5 – 对于可空字段规则中的值,.of() 函数将根据参数进行验证并返回相应的结果
示例
示例 1
import 'package:blueprint/blueprint.dart';
void main(List<String> arguments) {
//* use try/catch blocs to catch the failure message
try {
// simple one felid
matchMap(
// the json
{'name': 'queen'},
// the blue print
{'name': String},
// * you can use supported Felids only , they are listen in the readme.md file
throwable:true,
);
print('[?][blue_print] match result is ✅');
} catch (e) {
print(e);
print('[?][blue_print] match result is ❌');
}
}
示例 2
void main(List<String> arguments) {
//* use try/catch blocs to catch the failure message
try {
// ? validate against lists
matchMap(
{
'ids': [10, 11, 17]
},
{
'ids': ListF,
// ? or you can determine the list items type
// 'ids' : ListF(IntF()),
},
throwable:true,
);
print('[?][blue_print] match result is ✅');
} catch (e) {
print(e);
print('[?][blue_print] match result is ❌');
}
}
示例 3
void main(List<String> arguments) {
//* use try/catch blocs to catch the failure message
try {
// * full example
matchMap(
{
'name': 'ahmed',
'age': 25,
'args': [
{'foo': 5},
],
'passport': {
'id': 1,
'type': 'royal',
'created_at': '10-11-17',
}
},
// the blue print
{
'name': StringF,
'age': IntF,
'args': ListF(MapF.of({'foo': IntF})),
'passport': MapF.of({
'id': IntF,
'type': StringF,
'created_at': StringF,
})
},
throwable:true,
);
print('[?][blue_print] match result is ✅');
} catch (e) {
print(e);
print('[?][blue_print] match result is ❌');
}
}
