How to Convert GraphQLSchema Object to Type Defini

2019-08-01 03:42发布

问题:

Let's say i have a GraphQL Schema like:

type author {
    id: Int
    name: String
    rating: Int  
}

You can use this type definition to generate an executable schema that can be queried on.

But in case i don't have the above type definitions, but only have GraphQLSchema object obtained through the introspection query, how do i generate the above type definitions?

I checked out graphql/utilities which had a printSchema method, that accepts a GraphQLSchema object and prints a string. But i can't seem to filter the output for a particular node alone, since i don't want the entire schema. Parsing the string output is not desirable.

Pointing to right methods is appreciated.

回答1:

Unlike printSchema it is not mentioned in the docs, but graphql-js exports printType method exactly for this! See in the sources. For example with graphql-iso-date.

const { printType } = require('graphql');
const { GraphQLDate } = require('graphql-iso-date');

console.log(printType(GraphQLDate));

It prints:

"""
A date string, such as 2007-12-03, compliant with the `full-date` format
outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for
representation of dates and times using the Gregorian calendar.
"""
scalar Date

Which can be simply put to makeExecutableSchema functions typeDefs parameter.