UNPKG

5.09 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.print = void 0;
4const visitor_1 = require("graphql/language/visitor");
5const prettify_1 = require("./helpers/prettify");
6function print(ast, options = {}) {
7 return (0, visitor_1.visit)(ast, {
8 leave: (node) => {
9 const fn = printDocASTReducer(options);
10 const visitor = fn[node.kind];
11 if (visitor) {
12 return visitor(node);
13 }
14 return null;
15 },
16 });
17}
18exports.print = print;
19function printDocASTReducer({ clientVarName = 'client', transformVariableName = (x) => x, thenCode }) {
20 return {
21 Name: (node) => node.value,
22 Variable: (node) => transformVariableName(node.name),
23 NamedType: ({ name }) => name,
24 ListType: ({ type }) => '[' + type + ']',
25 NonNullType: ({ type }) => type,
26 Directive: ({ name, arguments: args }) => '',
27 IntValue: ({ value }) => value,
28 FloatValue: ({ value }) => value,
29 StringValue: ({ value, block: isBlockString }, key) => JSON.stringify(value),
30 BooleanValue: ({ value }) => (value ? 'true' : 'false'),
31 NullValue: () => 'null',
32 EnumValue: ({ value }) => `'${value}'`,
33 ListValue: ({ values }) => '[' + join(values, ', ') + ']',
34 ObjectValue: ({ fields }) => '{' + join(fields, ', ') + '}',
35 ObjectField: ({ name, value }) => name + ': ' + value,
36 // Document
37 Document: (node) => join(node.definitions, '\n\n') + '\n',
38 OperationDefinition(node) {
39 const selectionSet = node.selectionSet;
40 // Anonymous queries with no directives or variable definitions can use
41 // the query short form.
42 let code = join(node.variableDefinitions, '\n');
43 if (node.variableDefinitions.length) {
44 code = '// variables\n' + code;
45 code += '\n\n';
46 }
47 code += `${clientVarName}.${node.operation}(` + selectionSet + ')';
48 if (thenCode) {
49 code += `.then(${thenCode})`;
50 }
51 return (0, prettify_1.prettify)(code, 'typescript');
52 },
53 VariableDefinition: ({ variable, type, defaultValue, directives }) => {
54 return 'var ' + variable.replace('$', '');
55 },
56 SelectionSet: ({ selections }) => block(selections),
57 Field: ({ alias, name, arguments: args, directives, selectionSet }) => {
58 if (args.length == 0 && !join([selectionSet])) {
59 return name + ': true';
60 }
61 if (args.length == 0) {
62 return name + ': ' + join([selectionSet]);
63 }
64 const argsAndFields = join([block(args), ',', selectionSet]);
65 return name + ': ' + wrap('[', argsAndFields, ']');
66 },
67 // join(directives, ' '),
68 Argument: ({ name, value = '' }) => {
69 if (typeof value === 'string') {
70 return name + ': ' + transformVariableName(value.replace('$', ''));
71 }
72 console.error(`unhandled type, received ${JSON.stringify(value)} as Argument`);
73 return '';
74 },
75 // Fragments
76 FragmentSpread: ({ name, directives }) => {
77 // TODO FragmentSpread
78 return '...' + name + ',';
79 },
80 InlineFragment: ({ typeCondition, directives, selectionSet }) => {
81 // console.log({ selectionSet, directives, typeCondition });
82 return join(['', wrap('on_', typeCondition), ':', selectionSet], ' ');
83 },
84 FragmentDefinition: ({ name, typeCondition, variableDefinitions, directives, selectionSet }) => {
85 // TODO FragmentDefinition
86 // Note: fragment variable definitions are experimental and may be changed
87 // or removed in the future.
88 return `const ${name} = ` + selectionSet;
89 },
90 // Directive
91 };
92}
93/**
94 * Given maybeArray, print an empty string if it is null or empty, otherwise
95 * print all items together separated by separator if provided
96 */
97function join(maybeArray, separator = '') {
98 var _a;
99 return (_a = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter((x) => x).join(separator)) !== null && _a !== void 0 ? _a : '';
100}
101/**
102 * Given array, print each item on its own line, wrapped in an
103 * indented "{ }" block.
104 */
105function block(array) {
106 return array && array.length !== 0 ? '{\n' + indent(join(array, ',\n')) + '\n}' : '';
107}
108/**
109 * If maybeString is not null or empty, then wrap with start and end, otherwise
110 * print an empty string.
111 */
112function wrap(start, maybeString, end = '') {
113 return maybeString ? start + maybeString + end : '';
114}
115function indent(maybeString) {
116 return maybeString && ' ' + maybeString.replace(/\n/g, '\n ');
117}
118function isMultiline(string) {
119 return string.indexOf('\n') !== -1;
120}
121function hasMultilineItems(maybeArray) {
122 return maybeArray && maybeArray.some(isMultiline);
123}
124//# sourceMappingURL=printer.js.map
\No newline at end of file