How can simple object types [1] such as interfaces &/ classes be generated from GraphQL schema definitions into Dart?
- Motivation
- One single source of truth: GraphQL schema
- From GraphQL all plain simple types are generated into multiple languages
- in our case Typescript and Dart
- what we've tried so far
- All solutions related [2] - even forks - does not do simple types
- Possible DIY approaches we know of
- GraphQL Code Generator [3]
- quicktype similar alternatives [4]
GraphQL into Typescript example
Given this schema definition
type Person {
age: Int
name: String!
}
Running this script
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'
});
Output
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