GraphQL Code Generator plugin for generating .graphql files from GraphQL schemas
npx @tessl/cli install tessl/npm-graphql-codegen--schema-ast@4.1.0Schema AST is a GraphQL Code Generator plugin that generates formatted .graphql files from GraphQL schemas. It prints merged schemas as string output with configurable options for directives, introspection types, description formatting, sorting, and Apollo Federation support.
npm install @graphql-codegen/schema-astimport { plugin, validate, transformSchemaAST, type SchemaASTConfig } from "@graphql-codegen/schema-ast";
import { GraphQLSchema, DocumentNode } from "graphql";
import { Types } from "@graphql-codegen/plugin-helpers";For CommonJS:
const { plugin, validate, transformSchemaAST } = require("@graphql-codegen/schema-ast");import { buildSchema } from "graphql";
import { plugin } from "@graphql-codegen/schema-ast";
// Define a more comprehensive schema
const schema = buildSchema(`
directive @auth on FIELD_DEFINITION
type User {
id: ID!
name: String!
email: String @auth
}
type Query {
hello: String
user(id: ID!): User
}
`);
// Generate schema AST string with basic configuration
const schemaOutput = await plugin(schema, [], {
includeDirectives: false,
includeIntrospectionTypes: false,
commentDescriptions: false,
sort: false
});
console.log(schemaOutput);
// Output: type Query {\n hello: String\n user(id: ID!): User\n}\n\ntype User {\n id: ID!\n name: String!\n email: String\n}Main plugin function that transforms GraphQL schema to formatted string output.
/**
* Main plugin function that transforms GraphQL schema to string
* @param schema - The GraphQL schema to transform
* @param documents - Document files (unused by this plugin)
* @param config - Plugin configuration options
* @returns Promise resolving to formatted schema string
*/
function plugin(
schema: GraphQLSchema,
documents: any,
config: SchemaASTConfig
): Promise<string>;Usage Example:
import { buildSchema } from "graphql";
import { plugin } from "@graphql-codegen/schema-ast";
const schema = buildSchema(`
directive @auth on FIELD_DEFINITION
type User {
id: ID!
name: String @auth
}
type Query {
user(id: ID!): User
}
`);
// Include directives in output
const withDirectives = await plugin(schema, [], {
includeDirectives: true
});
// Use comment-style descriptions (for GraphQL < 16)
const withComments = await plugin(schema, [], {
commentDescriptions: true
});
// Remove all descriptions from output
const withoutDescriptions = await transformSchemaAST(schema, {
disableDescriptions: true
});Validates output file extension to ensure compatibility with GraphQL file formats.
/**
* Validation function that ensures output file has correct extension
* @param schema - GraphQL schema (unused)
* @param documents - Document files (unused)
* @param config - Plugin config (unused)
* @param outputFile - Output file path to validate
* @param allPlugins - All configured plugins
* @throws Error if single plugin and file extension not supported
*/
function validate(
schema: GraphQLSchema,
documents: Types.DocumentFile[],
config: SchemaASTConfig,
outputFile: string,
allPlugins: Types.ConfiguredPlugin[]
): Promise<void>;Validation Rules:
Transforms schema AST with various configuration options including federation support.
/**
* Transforms schema AST with various configuration options
* @param schema - Input GraphQL schema
* @param config - Configuration object with transformation options
* @param config.federation - Remove federation-specific types when true
* @param config.includeIntrospectionTypes - Add introspection query fields
* @param config.disableDescriptions - Remove all descriptions from schema
* @param config.sort - Enable schema sorting
* @returns Object containing transformed schema and AST
*/
function transformSchemaAST(
schema: GraphQLSchema,
config: {
federation?: boolean;
includeIntrospectionTypes?: boolean;
disableDescriptions?: boolean;
sort?: boolean;
[key: string]: any;
}
): {
schema: GraphQLSchema;
ast: DocumentNode;
};Configuration Options:
federation: Remove federation-specific types when trueincludeIntrospectionTypes: Add introspection query fieldsdisableDescriptions: Remove all descriptions from schemasort: Enable schema sortinginterface SchemaASTConfig {
/**
* Include directives in schema output
* @default false
*/
includeDirectives?: boolean;
/**
* Include introspection types in schema output
* @default false
*/
includeIntrospectionTypes?: boolean;
/**
* Print descriptions as comments using # instead of """
* @default false
*/
commentDescriptions?: boolean;
/**
* Enable/disable sorting of schema elements
* @default false
*/
sort?: boolean;
/**
* Remove all descriptions from the schema output
* @default false
*/
disableDescriptions?: boolean;
/**
* Enable federation schema transformations
*/
federation?: boolean;
/**
* Remove all descriptions from the schema output
* @default false
*/
disableDescriptions?: boolean;
}Configuration Examples:
// Minimal configuration
const basicConfig: SchemaASTConfig = {};
// Full configuration
const fullConfig: SchemaASTConfig = {
includeDirectives: true,
includeIntrospectionTypes: true,
commentDescriptions: false,
sort: false,
federation: false,
disableDescriptions: false
};
// Federation schema
const federationConfig: SchemaASTConfig = {
federation: true,
includeDirectives: false
};
// Schema without descriptions
const noDescriptionsConfig: SchemaASTConfig = {
disableDescriptions: true
};This plugin is designed to work within the GraphQL Code Generator ecosystem:
// codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
schema: './src/schema.graphql',
generates: {
'output/schema.graphql': {
plugins: ['schema-ast'],
config: {
includeDirectives: true,
sort: false
}
}
}
};
export default config;The plugin handles several error scenarios:
// Example error handling
try {
await validate(schema, [], {}, 'output.ts', [{ 'schema-ast': {} }]);
} catch (error) {
console.error('Validation failed:', error.message);
// Error: Plugin "schema-ast" requires extension to be ".graphql" or ".gql" or ".graphqls"!
}// Core GraphQL types from 'graphql' package
interface GraphQLSchema {
// Complete GraphQL schema representation
getQueryType(): GraphQLObjectType | null;
getMutationType(): GraphQLObjectType | null;
getSubscriptionType(): GraphQLObjectType | null;
getTypeMap(): TypeMap;
getDirectives(): readonly GraphQLDirective[];
// Additional schema methods...
}
interface DocumentNode {
// AST document node from 'graphql' package
readonly kind: 'Document';
readonly definitions: readonly DefinitionNode[];
}
interface DefinitionNode {
readonly kind: string;
readonly loc?: Location;
}
// Plugin helper types from '@graphql-codegen/plugin-helpers'
namespace Types {
interface DocumentFile {
document: DocumentNode;
rawSDL?: string;
content: string;
filePath: string;
}
interface ConfiguredPlugin {
[name: string]: any;
}
}
// Plugin function types
type PluginFunction<T = any> = (
schema: GraphQLSchema,
documents: Types.DocumentFile[],
config: T
) => Promise<string> | string;
type PluginValidateFn<T = any> = (
schema: GraphQLSchema,
documents: Types.DocumentFile[],
config: T,
outputFile: string,
allPlugins: Types.ConfiguredPlugin[]
) => Promise<void> | void;