如何从 GraphQL 模式定义将简单的对象类型 [1](例如接口(interface)和/类)生成到 Dart 中?
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
您可以根据需要设置自定义标量类型。编辑:
现在有一个 expanded version作为 PR .
可以在
lib/
之外生成它们没有导入路径冲突,通过选择退出选项 dynamic_import_path: false
.type_override
键也不再需要以小写形式显式编写。
关于flutter - 如何从 GraphQL 生成 Dart - graphql 到 dart 生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62590497/