【问题标题】:How to generate Dart from GraphQL - graphql to dart generator如何从 GraphQL 生成 Dart - graphql 到 dart 生成器
【发布时间】:2020-10-16 19:19:03
【问题描述】:

如何将简单的对象类型 [1](如接口和/类)从 GraphQL 模式定义生成到 Dart 中?

  • 动机
    • 单一事实来源:GraphQL 架构
    • 从 GraphQL 所有普通简单类型都生成为多种语言
      • 在我们的例子中是 Typescript 和 Dart
  • 到目前为止我们已经尝试过什么
    • 所有与 [2] 相关的解决方案 - 甚至分叉 - 都不做简单类型
  • 我们知道的可能的 DIY 方法
    • GraphQL 代码生成器 [3]
    • 快速键入类似的替代方案 [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

【问题讨论】:

  • 你可以试试我的包graphql_to_dart。它正在进行中,但适用于输出类型。
  • 非常感谢您如此快速地回复,也感谢您提供这个包裹,我们将把我们的问题放在那里。

标签: flutter dart types graphql code-generation


【解决方案1】:

我个人尝试使用Artemis 或希望Apollo 进行分支,但@Ryosukegraphql_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。 通过选择退出选项dynamic_import_path: false,可以在lib/ 之外生成它们而不会出现导入路径冲突。

type_override 键也不再需要显式小写。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2021-07-12
    • 2020-12-05
    • 2023-03-25
    • 2019-05-02
    • 2013-05-06
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多