generate-graphql-code

Generate TypeScript code from GraphQL endpoint url or introspection json file.
This module will do the following for you:
- Generate all types found in the schema.
- Generate a factory function which you can use to create your GraphQL client.
To get started, checkout the example directory or take a look at the generated files.
Table of contents:
Installation
pnpm i generate-graphql-code -D
npm i generate-graphql-code --save-dev
Preview
In the following preview, the client is created with the factory function generated by generate-graphql-code.

Usage
With the command:
npx generate-graphql-code --config ./config.json
An example configuration file:
{
"files": [
{
"filename": "./graphql/example-introspection.json",
"output": "./generated/example.ts"
},
{
"endpoint": { "url": "https://countries.trevorblades.com/" },
"output": "./generated/countries.ts"
}
]
}
Or you can use the generate function programmatically:
import generate from 'generate-graphql-code'
generate({
files: [
{
filename: './graphql/example-introspection.json',
output: './generated/example.ts'
},
{
endpoint: { url: 'https://countries.trevorblades.com/' },
output: './generated/countries.ts'
}
]
})
Configuration file format
export interface ConfigurationFile {
global?: Options
files?: SchemaFile[]
}
export interface SchemaFile {
output: string
filename?: string
endpoint?: {
url: string
headers?: Record<string, any>
headersFile?: string
}
options?: Options
skipGlobalScalarTypes?: boolean
skip?: boolean
}
export interface Options {
scalarTypes?: Record<string, string> | [string, string][]
argsSuffix?: string
fieldsSuffix?: string
skipLintComments?: boolean
skipWarningTip?: boolean
skipWrappingArgsEnum?: boolean
skipArgs?: boolean
skipFields?: boolean
skipFactory?: boolean
skipQuery?: boolean
skipQueries?: boolean
skipMutation?: boolean
skipMutations?: boolean
headers?: string[]
footers?: string[]
}
How to get introspection JSON?
Open your GraphiQL page, paste the following graphql code to query the introspection:
query IntrospectionQuery {
__schema {
queryType {
name
}
mutationType {
name
}
subscriptionType {
name
}
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type {
...TypeRef
}
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}