Search code examples
javascriptgraphqlrelayjsgraphql-js

how to obtain .graphql file from GraphQLSchema javascript object?


I am creating a new graphQL schema with graphql-js but is not going to be served through http, is going to be used as a local graphql service. I need to obtain the schema for this graphql in json format to merge it with another schema. I have been using get-graphql-schema to obtain the schema from a server, but this is not going to work in my case.

What I would like is to obtain the json with the schema from the GraphQLSchema object that I obtain after make new GraphQLSchema({ query, mutation });

I'm sure that is quite simple but I'm a bit stuck with that. Thank you!


Solution

  • Since you want a .graphql file from a GraphQLSchema object created locally you can just use printSchema to print it then write it to a file

    import { printSchema } from 'graphql';
    import Query from './Query';
    import fs from 'fs';
    
    const schema = new GraphQLSchema({
      query: Query
    });
    
    const fileData = printSchema(schema);
    
    fs.writeFile('/path/to/schema.graphql', fileData, error => {
      // handle error
    });
    

    the get-graphql-schema package can only be used with a graphql-server endpoint. That package first sends an introspection query to get the JSON representation, then reconstructs a client (non-executable) schema using graphql-js buildClientSchema then uses printSchema to finally output the schema language representation that can be put in a .graphql file. Since you already have the GraphQLSchema object locally you can just skip the first 2 steps and print the schema.