flutter - 如何从 GraphQL 生成 Dart - graphql 到 dart 生成器
问题描述
如何从 GraphQL 模式定义将简单的对象类型 [1](例如接口和/类)生成到 Dart 中?
- 动机
- 一个单一的事实来源:GraphQL 模式
- 从 GraphQL 所有简单的类型都生成为多种语言
- 在我们的例子中,Typescript 和 Dart
- 到目前为止我们已经尝试过的
- 所有与 [2] 相关的解决方案 - 甚至分叉 - 都不做简单类型
- 我们知道的可能的DIY方法
- GraphQL 代码生成器 [3]
- quicktype 类似的替代品 [4]
GraphQL 到 Typescript 示例
鉴于此架构定义
type Person {
age: Int
name: String!
}
运行此脚本
import { GraphQLDefinitionsFactory } from '@nestjs/graphql';
import { join } from 'path';
const definitionsFactory = new GraphQLDefinitionsFactory();
definitionsFactory.generate({
typePaths: ['./**/*.graphql'],
path: join(process.cwd(), './class.ts'),
outputAs: 'class'
});
definitionsFactory.generate({
typePaths: ['./src/**/*.graphql'],
path: join(process.cwd(), './interface.ts'),
outputAs: 'interface'
});
输出
export interface Person {
age?: number;
name: string;
}
export class Person {
age?: number;
name: string;
}
1:简单对象类型应该只是简单的普通对象类型,没有注释,编码和解码逻辑等。 2:https
://github.com/gql-dart/gql
3:https
://graphql-code-generator.com
4 :https ://app.quicktype.io
解决方案
我个人尝试使用Artemis或希望Apollo能够扩展,但@Ryosuke的graphql_to_dart是直截了当且精简的。
如果您已经有一个 GraphQL 端点,并且您的架构已启动并正在运行,您只需要graphql_config.yaml
像这样设置它:
package_name: example
graphql_endpoint: http://example.com/graphql
models_directory_path: lib/graphql/models/
给定模式定义
type Person {
age: Int
name: String!
}
.dart 输出
class Person{
int age;
String name;
Person({
this.age,this.name
});
Person.fromJson(Map<String, dynamic> json){
age = json['age'];
name = json['name'];
}
Map toJson(){
Map _data = {};
_data['age'] = age;
_data['name'] = name;
return _data;
}
}
使用附加选项type_override
,您可以根据需要设置自定义标量类型。
编辑:
现在有一个扩展版本PR。lib/
通过选择退出选项,可以在没有导入路径冲突的情况下生成它们dynamic_import_path: false
。
键也不再需要以type_override
小写形式显式编写。
推荐阅读
- python - 3d 网格上描述符的着色函数
- java - 下载二进制文件抛出 org.jvnet.mimepull.MIMEParsingException: java.io.IOException: Stream Closed
- scala - 如何从scala中的列表中创建一个元组?
- sql - 复杂的 JOIN 查询 SQL Server
- javascript - Cocos2djs 中的 FPS 下降
- matlab - 将文本文件中的整数存储到变量数组中
- ios - 使用手表和 iPhone 的蓝牙连接的距离
- python - Pytest、setup_method 和类级模拟
- flutter - 向日期添加天数无法正常工作
- php - 如何在 Windows plesk 服务器中重写 htaccess 规则