Pothos
Guide

Printing Schemas

Sometimes it's useful to have an SDL version of your schema. To do this, you can use some tools from the graphql package to write your schema out as SDL to a file.

import { writeFileSync } from 'node:fs';
import { printSchema } from 'graphql';
import SchemaBuilder from '@pothos/core';

const builder = new SchemaBuilder({});

builder.queryType({
  fields: (t) => ({
    hello: t.string({
      args: {
        name: t.arg.string(),
      },
      resolve: (parent, { name }) => `hello, ${name || 'World'}`,
    }),
  }),
});

const schema = builder.toSchema();
const schemaAsString = printSchema(schema);

writeFileSync('./schema.graphql', `${schemaAsString}\n`);

builder.toSchema() sorts the schema by default.

Save the example as print-schema.ts and run it with a TypeScript runner:

npm install --save-dev tsx
npx tsx print-schema.ts

In an existing application, import your exported schema instead of creating another builder. Keep schema construction separate from starting your server so this script does not open a listening port. The generated SDL can be checked into source control for schema reviews or read by client tooling.

printSchema prints type definitions, not resolver functions or backing data. It also does not preserve applied custom directives; use a printer that supports those directives if downstream tools need them, such as when exporting a federation subgraph.

Using graphql-code-generator

An alternative to printing your schema directly is to generate your schema file using graphql-code-generator.

You can add the schema-ast plugin to have graphql-code-generator generate your schema file for you.

See Generating Client Types for more details

On this page