首页 > 解决方案 > 如何从 GraphQL 生成 Dart - graphql 到 dart 生成器

问题描述

如何从 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

标签: flutterdarttypesgraphqlcode-generation

解决方案


我个人尝试使用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,您可以根据需要设置自定义标量类型。

编辑:

现在有一个扩展版本PRlib/通过选择退出选项,可以在没有导入路径冲突的情况下生成它们dynamic_import_path: false

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


推荐阅读