GraphQL schema JSON Writer
Extension to graphSchemaToJson to write the schema generated from a GraphQL type def to various outputs:
- Typescript source files
- GraphQL type def files
Also includes accessor functionality to better work with the schema object generated.
Usage
Person: fields: name: type: 'String' directives: {} isNullable: false isList: false age: type: 'Int' directives: range: min: 0 max: 130 isNullable: false isList: false gender: type: 'Gender' directives: {} isNullable: false isList: false directives: {} type: 'Object' implements: Gender: fields: 'male' 'female' directives: {} type: 'Enum'
Accessor
;;const schemaByType filteredSchema = accessor;/// ... generate JSON schemaconst jsSchema = ; // schema where all entries with keys starting with __ are filtered outconst filteredMap = ; // soreted by typeconst typeMap = ;console;
Object: Person: // .... Enum: Gender: // ...
Writer
;;const writeToTypeDef = writer;/// ... generate JSON schemaconst jsSchema = ; // schema where all entries with keys starting with __ are filtered outconst typeDef = ;console;
Should output the (original) GraphqL type def, nicely formatted:
type Person { name: String! age: Int! @range(min: 0, max: 130) gender: Gender!} enum Gender { male female}
Writing typescript source files
The writer also supports writing a TypeScript class
, complete with:
extends
class- implements
interfaces
- decorators for class itself and fields and properties
- imports for the decorators, interfaces and class extended
;;/// ... generate JSON schemaconst jsSchema = ;const classType = ; const importsMap = Range: "class-validator" BaseEntity: "typeorm" Entity: "typeorm";const body = classType;console;
Output a TypeScript class with decorators
;;
Writing source files
Use the SourceFile
class to write source files to disk:
; // include typical import maps, such as for typeorm and class-validator;; ;await srcFileWriter.writeTypeDefsjsSchema, writeOpts;await srcFileWriter.writeIndexFiles;
Files written, assuming __dirname
is /src
, using default flat
strategy:
/src /db /models Person.ts Gender.ts index.ts
Using defaults:
;// ...await writeTypeDefsjsSchema, ;
Files written using type-folder
strategy:
/src /db /models /class Person.ts index.ts /enum/ Gender.ts index.ts index.ts
Note: The SourceFileWriter
has not yet been fully tested and could use some futher refactoring. It should include enough building blocks for you to compose a solution to fit your needs ;)
Imports map
Imports maps now have support for aliases
importsMap =;
Will result in an aliased import:
import { Range as range } from 'validator';
Use cases
This class writer could be used for writing classed for TypeORM, NestJS or TypeGraphQL etc.
Note that the class writer supports passing decorators
in place of directives
.
License
MIT