How can simple object types [1] such as interfaces &/ classes be generated from GraphQL schema definitions into Dart?
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: Simple Object Types should be just simple plain object types without annotations, encoding and decoding logic etc.
2: https://github.com/gql-dart/gql
3: https://graphql-code-generator.com
4: https://app.quicktype.io
I personally tried to use Artemis or hoped Apollo was branching out, but @Ryosuke's graphql_to_dart is straight forward and lean.
If you already have a GraphQL endpoint with your schema up and running, you just need to set up its graphql_config.yaml for example like this:
package_name: example
graphql_endpoint: http://example.com/graphql
models_directory_path: lib/graphql/models/
type Person {
    age: Int
    name: String!
}
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;
  }
}
With the additional option type_override you can set custom scalar types as you prefer them.
Edit:
There is now an expanded version as PR.
With the possibility to generate them outside of lib/ without import path conflicts, through an opt-out option dynamic_import_path: false.
The type_override keys also don't need to be explicitly written in lower case anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With