UNPKG

apollo-codegen

Version:

Generate API code or type annotations based on a GraphQL schema and query documents

86 lines (75 loc) 2.02 kB
import { isType, GraphQLType, GraphQLScalarType, GraphQLEnumType, GraphQLInputObjectType, } from 'graphql'; import { LegacyCompilerContext } from './compiler/legacyIR'; export default function serializeToJSON(context: LegacyCompilerContext) { return serializeAST({ operations: Object.values(context.operations), fragments: Object.values(context.fragments), typesUsed: context.typesUsed.map(serializeType), }, '\t'); } export function serializeAST(ast: any, space?: string) { return JSON.stringify(ast, function(_, value) { if (isType(value)) { return String(value); } else { return value; } }, space); } function serializeType(type: GraphQLType) { if (type instanceof GraphQLEnumType) { return serializeEnumType(type); } else if (type instanceof GraphQLInputObjectType) { return serializeInputObjectType(type); } else if (type instanceof GraphQLScalarType) { return serializeScalarType(type); } else { throw new Error(`Unexpected GraphQL type: ${type}`); } } function serializeEnumType(type: GraphQLEnumType) { const { name, description } = type; const values = type.getValues(); return { kind: 'EnumType', name, description, values: values.map(value => ( { name: value.name, description: value.description, isDeprecated: value.isDeprecated, deprecationReason: value.deprecationReason } )) } } function serializeInputObjectType(type: GraphQLInputObjectType) { const { name, description } = type; const fields = Object.values(type.getFields()); return { kind: 'InputObjectType', name, description, fields: fields.map(field => ({ name: field.name, type: String(field.type), description: field.description, defaultValue: field.defaultValue })) } } function serializeScalarType(type: GraphQLScalarType) { const { name, description } = type; return { kind: 'ScalarType', name, description } }