如何从 GraphQL 生成 Dart - graphql 到 dart 生成器

How to generate Dart from GraphQL - graphql to dart generator

如何从 GraphQL 模式定义将简单对象类型 [1](例如接口和/类 生成到 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 or hoped Apollo was branching out, but @Ryosuke's 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 as PR。 通过选择退出选项 dynamic_import_path: false.

,可以在 lib/ 之外生成它们而不会发生导入路径冲突

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