Flutter数据验证与模式管理插件leto_schema的使用
Flutter数据验证与模式管理插件leto_schema的使用
leto_schema
是一个在 Dart 中实现 GraphQL 类型系统的库。它支持任何运行 Dart 的平台,并且设计决策尽可能接近 JavaScript 参考实现。此库包含了构建所有 GraphQL 类型的功能。
主要功能
- 所有 GraphQL 类型:如
String
,Int
,Float
,Boolean
,GraphQLObjectType
,GraphQLUnionType
,GraphQLEnumType
,GraphQLInputObjectType
,GraphQLListType
,GraphQLNonNullType
等。 - GraphQL 模式定义:包括查询类型、变异类型和订阅类型。
- 数据验证:可以对输入数据进行验证。
- 序列化和反序列化:支持数据的序列化和反序列化。
- 自定义验证规则:允许用户自定义验证逻辑。
使用示例
// 忽略文件中的打印警告
// ignore_for_file: avoid_print
import 'package:leto_schema/leto_schema.dart';
// 定义 Todo 查询类型
final GraphQLSchema todoSchema = GraphQLSchema(
queryType: objectType('Todo', fields: [
field(
'text',
graphQLString.nonNull(),
resolve: resolveToNull,
),
field(
'created_at',
graphQLDate,
resolve: resolveToNull,
),
]),
);
/// 默认解析器,总是返回 null
Object? resolveToNull(Object? _, Object? __) => null;
void main() {
// 验证
final validation = todoSchema.queryType!.validate(
'@root',
{
'foo': 'bar',
'text': null,
'created_at': 24,
},
);
if (validation.successful) {
print('这是有效的数据!');
} else {
print('无效的数据。');
for (final s in validation.errors) {
print(' * $s');
}
}
// 序列化
print(todoSchema.queryType!.serialize({
'text': '整理你的房间!',
'created_at': DateTime.now().subtract(const Duration(days: 10))
}));
}
详细说明
GraphQL 模式定义
每个 GraphQLSchema
都需要一个作为根查询类型的 GraphQLObjectType
,以及可选的 GraphQLObjectType
用于变异和订阅根。
final GraphQLSchema todoSchema = GraphQLSchema(
queryType: objectType('Todo', fields: [
field(
'text',
graphQLString.nonNull(),
resolve: resolveToNull,
),
field(
'created_at',
graphQLDate,
resolve: resolveToNull,
),
]),
);
数据验证
你可以通过调用 validate
方法来验证输入数据。如果验证成功,则 GraphQLType.deserialize
方法应该返回 Dart 类型的一个实例。
final validation = todoSchema.queryType!.validate(
'@root',
{
'foo': 'bar',
'text': null,
'created_at': 24,
},
);
if (validation.successful) {
print('这是有效的数据!');
} else {
print('无效的数据。');
for (final s in validation.errors) {
print(' * $s');
}
}
序列化
序列化允许你将数据转换为字符串形式。
print(todoSchema.queryType!.serialize({
'text': '整理你的房间!',
'created_at': DateTime.now().subtract(const Duration(days: 10))
}));
更多关于Flutter数据验证与模式管理插件leto_schema的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter数据验证与模式管理插件leto_schema的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
leto_schema
是一个用于 Flutter 和 Dart 的插件,用于构建 GraphQL 模式并执行数据验证。它允许你定义 GraphQL 类型、查询、突变和订阅,并提供了强大的数据验证功能。虽然 leto_schema
并不是一个专门的数据验证库,但它可以与其他验证库结合使用,或者利用 GraphQL 的类型系统来进行验证。
以下是如何在 Flutter 项目中使用 leto_schema
的基本步骤,并结合数据验证功能。
1. 添加依赖
在你的 pubspec.yaml
文件中添加 leto_schema
依赖:
dependencies:
leto_schema: ^0.5.0
然后运行 flutter pub get
安装依赖。
2. 定义 GraphQL 模式
使用 leto_schema
定义 GraphQL 模式。下面是一个简单的例子,包括一个查询和一个数据类型。
import 'package:leto_schema/leto_schema.dart';
import 'package:leto_schema/leto_schema.dart' as gql;
// 定义一个数据类型
final userType = gql.objectType(
'User',
description: 'A user in the system',
fields: [
gql.field('id', gql.idType),
gql.field('name', gql.stringType),
gql.field('age', gql.intType),
gql.field('email', gql.stringType),
],
);
// 定义查询
final queryType = gql.objectType(
'Query',
fields: [
gql.field(
'user',
userType,
description: 'Get a user by ID',
inputs: [
gql.inputField('id', gql.idType),
],
resolve: (_, ctx) {
final id = ctx.args['id'];
// 这里可以添加验证逻辑
if (id == null) {
throw Exception('ID is required');
}
// 模拟返回用户数据
return {'id': id, 'name': 'Alice', 'age': 25, 'email': 'alice@example.com'};
},
),
],
);
// 创建 GraphQL 模式
final schema = gql.graphQLSchema(
queryType: queryType,
);
3. 执行查询
使用 graphQLExecute
执行查询:
import 'package:leto_schema/leto_schema.dart' as gql;
void main() async {
final result = await gql.graphQLExecute(
schema,
gql.parse('''
query {
user(id: "1") {
id
name
age
email
}
}
'''),
);
print(result.data);
}
4. 数据验证
leto_schema
本身并不提供复杂的验证功能,但你可以通过以下方式实现验证:
4.1 使用内置类型系统
GraphQL 的类型系统(如 String
、Int
等)会自动验证输入数据的类型。例如,如果你传递一个字符串给 Int
字段,GraphQL 会返回错误。
4.2 自定义验证逻辑
在 resolve
函数中手动添加验证逻辑:
gql.field(
'user',
userType,
inputs: [
gql.inputField('id', gql.idType),
],
resolve: (_, ctx) {
final id = ctx.args['id'];
if (id == null || id.isEmpty) {
throw Exception('ID is required');
}
if (id.length != 36) {
throw Exception('Invalid ID format');
}
// 返回数据
return {'id': id, 'name': 'Alice', 'age': 25, 'email': 'alice@example.com'};
},
);
4.3 结合其他验证库
你可以使用其他 Dart 验证库(如 flutter_form_builder
或 validator_dart
)在 resolve
函数中进行更复杂的验证。例如:
import 'package:validator_dart/validator_dart.dart';
gql.field(
'user',
userType,
inputs: [
gql.inputField('email', gql.stringType),
],
resolve: (_, ctx) {
final email = ctx.args['email'];
if (!Validator.isEmail(email)) {
throw Exception('Invalid email format');
}
// 返回数据
return {'id': '1', 'name': 'Alice', 'age': 25, 'email': email};
},
);
5. 处理错误
GraphQL 会自动捕获异常并将其格式化为标准的 GraphQL 错误响应。你可以在客户端处理这些错误:
void main() async {
final result = await gql.graphQLExecute(
schema,
gql.parse('''
query {
user(id: "") {
id
name
}
}
'''),
);
if (result.hasErrors) {
print('Errors: ${result.errors}');
} else {
print(result.data);
}
}