UNPKG

2.12 kBPlain TextView Raw
1import {
2 isType,
3 GraphQLType,
4 GraphQLScalarType,
5 GraphQLEnumType,
6 GraphQLInputObjectType,
7 isEnumType,
8 isInputObjectType,
9 isScalarType
10} from "graphql";
11
12import { LegacyCompilerContext } from "./compiler/legacyIR";
13import { CompilerContext } from "./compiler";
14
15export default function serializeToJSON(
16 context: LegacyCompilerContext | CompilerContext
17) {
18 return serializeAST(
19 {
20 operations: Object.values(context.operations),
21 fragments: Object.values(context.fragments),
22 typesUsed: context.typesUsed.map(serializeType)
23 },
24 "\t"
25 );
26}
27
28export function serializeAST(ast: any, space?: string) {
29 return JSON.stringify(
30 ast,
31 function(_, value) {
32 if (isType(value)) {
33 return String(value);
34 } else {
35 return value;
36 }
37 },
38 space
39 );
40}
41
42function serializeType(type: GraphQLType) {
43 if (isEnumType(type)) {
44 return serializeEnumType(type);
45 } else if (isInputObjectType(type)) {
46 return serializeInputObjectType(type);
47 } else if (isScalarType(type)) {
48 return serializeScalarType(type);
49 } else {
50 throw new Error(`Unexpected GraphQL type: ${type}`);
51 }
52}
53
54function serializeEnumType(type: GraphQLEnumType) {
55 const { name, description } = type;
56 const values = type.getValues();
57
58 return {
59 kind: "EnumType",
60 name,
61 description,
62 values: values.map(value => ({
63 name: value.name,
64 description: value.description,
65 isDeprecated: value.isDeprecated,
66 deprecationReason: value.deprecationReason
67 }))
68 };
69}
70
71function serializeInputObjectType(type: GraphQLInputObjectType) {
72 const { name, description } = type;
73 const fields = Object.values(type.getFields());
74
75 return {
76 kind: "InputObjectType",
77 name,
78 description,
79 fields: fields.map(field => ({
80 name: field.name,
81 type: String(field.type),
82 description: field.description,
83 defaultValue: field.defaultValue
84 }))
85 };
86}
87
88function serializeScalarType(type: GraphQLScalarType) {
89 const { name, description } = type;
90
91 return {
92 kind: "ScalarType",
93 name,
94 description
95 };
96}