UNPKG

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