Generate a json schema without starting a server?

Viewed 1525

Is there a standalone tool to convert a modularized graphql schema to a json schema?

I have a graphql server using apollo-graphql and graphql-tools makeExecutableSchema. It follows the pattern described here

// schema.js
import { makeExecutableSchema } form 'graphql-tools';
const Author = `type Author { ... }`;
const Post   = `type Post   { ... }`;
const Query  = `type Query  { ... }`;

export const typeDefs = [Author, Post, Query];

export const schema = makeExecutableSchema({
  typeDefs: typeDefs,
  resolvers: { ... },
});

How can I create a schema.json form either typeDefs or schema?


I need a json schema to use relay-compiler or apollo-codegen. apollo-codegen includes this script to create a schema from a graphql server...

apollo-codegen introspect-schema http://localhost:8080/graphql --output schema.json

...but I want to create the schema, and run apollo-codegen, in an automated build. I don't want to create a server.


I would submit this as an answer, but the question has been marked off-topic ¯\_(ツ)_/¯

The answer from @daniel-rearden pointed me in the correct direction. makeExecutableSchema returns a GraphQLSchema so one can use graphql's printSchema and introspectionQuery to get json or graphql language representations of the schema.

// export.js
import { schema } from './schema.js'
import { graphql, introspectionQuery, printSchema } from 'graphql';

// Save json schema
graphql(schema, introspectionQuery).then(result => {
  fs.writeFileSync(
    `${yourSchemaPath}.json`,
    JSON.stringify(result, null, 2)
  );
});

// Save user readable type system shorthand of schema
fs.writeFileSync(
  `${yourSchemaPath}.graphql`,
  printSchema(schema)
);
1 Answers
Related