Back to Graphql Code Generator

Programmatic Usage

website/src/pages/docs/advanced/programmatic-usage.mdx

1.17.73.2 KB
Original Source

import { Callout } from '@theguild/components'

Programmatic Usage

GraphQL Code Generator also provides a complete programmatic API.

The programmatic API can be used if you need to customize the execution flow or write a tool that uses the codegen.

Basic Programmatic Usage

In order to use the programmatic API, start by importing codegen from @graphql-codegen/core:

ts
import { codegen } from '@graphql-codegen/core'

Then, create a configuration object (complete signature):

ts
import fs from 'node:fs'
import path from 'node:path'
import { buildSchema, printSchema, parse, GraphQLSchema } from 'graphql'
import * as typescriptPlugin from '@graphql-codegen/typescript'

const schema: GraphQLSchema = buildSchema(`type A { name: String }`)
const outputFile = 'relative/pathTo/filename.ts'
const config = {
  documents: [],
  config: {},
  // used by a plugin internally, although the 'typescript' plugin currently
  // returns the string output, rather than writing to a file
  filename: outputFile,
  schema: parse(printSchema(schema)),
  plugins: [
    // Each plugin should be an object
    {
      typescript: {} // Here you can pass configuration to the plugin
    }
  ],
  pluginMap: {
    typescript: typescriptPlugin
  }
}
<Callout> The `schema` field be a valid `GraphQLSchema` object. If you need to load your GraphQL schema from an external source (file, URL), you can use `loadSchema` from `@graphql-tools/load`. </Callout>

Notice that a plugin name key in pluginMap and plugins must match to identify a plugin and its configuration.

<Callout>You need to import the plugin in your favorite way; you can also use await import to lazy load it.</Callout>

Then, provide the config object to codegen:

ts
const output = await codegen(config)
await fs.writeFile(path.join(__dirname, outputFile), output, 'utf8')
console.log('Outputs generated!')
<Callout> We are using this API in the live demo on the GraphQL Code Generator website. [The code is here](https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/components/live-demo/generate.ts). </Callout> <Callout> **Loading schema and documents**

You can use one of the tools from @graphql-tools for file loading, schema merging, transformations and more.

</Callout>

Using the CLI instead of core

If you wish to have the benefits that cli package has (like loading schema and document files, parsing endpoints and more), you can use require() (or import) for @graphql-codegen/cli directly with Node.JS:

js
import { generate } from '@graphql-codegen/cli'

async function doSomething() {
  const generatedFiles = await generate(
    {
      schema: 'http://127.0.0.1:3000/graphql',
      documents: './src/**/*.graphql',
      generates: {
        [process.cwd() + '/models/types.d.ts']: {
          plugins: ['typescript']
        }
      }
    },
    true
  )
}

The return value should be of type Promise<FileOutput[]>.

<Callout type="warning"> This usage will not work in a browser environment because the `cli` package depends on Node.js internals and the file system. </Callout>