This repository has been archived by the owner on Aug 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
ExtractGQL.ts
374 lines (323 loc) · 11.6 KB
/
ExtractGQL.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// This file implements the extractgql CLI tool.
import fs = require('fs');
import path = require('path');
import {
parse,
DocumentNode,
OperationDefinitionNode,
FragmentDefinitionNode,
print,
DefinitionNode,
separateOperations,
} from 'graphql';
import {
getOperationDefinitions,
getFragmentNames,
isFragmentDefinition,
isOperationDefinition,
} from './extractFromAST';
import {
findTaggedTemplateLiteralsInJS,
eliminateInterpolations,
} from './extractFromJS';
import {
getQueryKey,
getQueryDocumentKey,
sortFragmentsByName,
applyQueryTransformers,
TransformedQueryWithId,
OutputMap,
QueryTransformer,
} from './common';
import {
addTypenameTransformer,
} from './queryTransformers';
import _ = require('lodash');
export type ExtractGQLOptions = {
inputFilePath: string,
outputFilePath?: string,
queryTransformers?: QueryTransformer[],
extension?: string,
inJsCode?: boolean,
};
export class ExtractGQL {
public inputFilePath: string;
public outputFilePath: string;
// Starting point for monotonically increasing query ids.
public queryId: number = 0;
// List of query transformers that a query is put through (left to right)
// before being written as a transformedQuery within the OutputMap.
public queryTransformers: QueryTransformer[] = [];
// The file extension to load queries from
public extension: string;
// Whether to look for standalone .graphql files or template literals in JavaScript code
public inJsCode: boolean = false;
// The template literal tag for GraphQL queries in JS code
public literalTag: string = 'gql';
// Given a file path, this returns the extension of the file within the
// file path.
public static getFileExtension(filePath: string): string {
const pieces = path.basename(filePath).split('.');
if (pieces.length <= 1) {
return '';
}
return pieces[pieces.length - 1];
}
// Reads a file into a string.
public static readFile(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
// Checks if a given path points to a directory.
public static isDirectory(path: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err) {
reject(err);
} else {
resolve(stats.isDirectory());
}
});
});
}
constructor({
inputFilePath,
outputFilePath = 'extracted_queries.json',
queryTransformers = [],
extension = 'graphql',
inJsCode = false,
}: ExtractGQLOptions) {
this.inputFilePath = inputFilePath;
this.outputFilePath = outputFilePath;
this.queryTransformers = queryTransformers;
this.extension = extension;
this.inJsCode = inJsCode;
}
// Add a query transformer to the end of the list of query transformers.
public addQueryTransformer(queryTransformer: QueryTransformer) {
this.queryTransformers.push(queryTransformer);
}
// Applies this.queryTransformers to a query document.
public applyQueryTransformers(document: DocumentNode) {
return applyQueryTransformers(document, this.queryTransformers);
}
// Just calls getQueryKey with this.queryTransformers as its set of
// query transformers and returns a serialization of the query.
public getQueryKey(definition: OperationDefinitionNode): string {
return getQueryKey(definition, this.queryTransformers);
}
// Just calls getQueryDocumentKey with this.queryTransformers as its
// set of query transformers and returns a serialization of the query.
public getQueryDocumentKey(
document: DocumentNode,
): string {
return getQueryDocumentKey(document, this.queryTransformers);
}
// Create an OutputMap from a GraphQL document that may contain
// queries, mutations and fragments.
public createMapFromDocument(document: DocumentNode): OutputMap {
const transformedDocument = this.applyQueryTransformers(document);
const queryDefinitions = getOperationDefinitions(transformedDocument);
const result: OutputMap = {};
queryDefinitions.forEach((transformedDefinition) => {
const transformedQueryWithFragments = this.getQueryFragments(transformedDocument, transformedDefinition);
transformedQueryWithFragments.definitions.unshift(transformedDefinition);
const docQueryKey = this.getQueryDocumentKey(transformedQueryWithFragments);
result[docQueryKey] = this.getQueryId();
});
return result;
}
// Given the path to a particular `.graphql` file, read it, extract the queries
// and return the promise to an OutputMap. Used primarily for unit tests.
public processGraphQLFile(graphQLFile: string): Promise<OutputMap> {
return new Promise<OutputMap>((resolve, reject) => {
ExtractGQL.readFile(graphQLFile).then((fileContents) => {
const graphQLDocument = parse(fileContents);
resolve(this.createMapFromDocument(graphQLDocument));
}).catch((err) => {
reject(err);
});
});
}
// Creates an OutputMap from an array of GraphQL documents read as strings.
public createOutputMapFromString(docString: string): OutputMap {
const doc = parse(docString);
const docMap = separateOperations(doc);
const resultMaps = Object.keys(docMap).map((operationName) => {
const document = docMap[operationName];
return this.createMapFromDocument(document);
});
return (_.merge({} as OutputMap, ...resultMaps) as OutputMap);
}
public readGraphQLFile(graphQLFile: string): Promise<string> {
return ExtractGQL.readFile(graphQLFile);
}
public readInputFile(inputFile: string): Promise<string> {
return Promise.resolve().then(() => {
const extension = ExtractGQL.getFileExtension(inputFile);
if (extension === this.extension) {
if (this.inJsCode) {
// Read from a JS file
return ExtractGQL.readFile(inputFile).then((result) => {
const literalContents = findTaggedTemplateLiteralsInJS(result, this.literalTag);
const noInterps = literalContents.map(eliminateInterpolations);
const joined = noInterps.join('\n');
return joined;
});
} else {
return this.readGraphQLFile(inputFile);
}
} else {
return '';
}
});
}
// Processes an input path, which may be a path to a GraphQL file
// or a directory containing GraphQL files. Creates an OutputMap
// instance from these files.
public processInputPath(inputPath: string): Promise<OutputMap> {
return new Promise<OutputMap>((resolve, reject) => {
this.readInputPath(inputPath).then((docString: string) => {
resolve(this.createOutputMapFromString(docString));
}).catch((err) => {
reject(err);
});
});
}
public readInputPath(inputPath: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
ExtractGQL.isDirectory(inputPath).then((isDirectory) => {
if (isDirectory) {
console.log(`Crawling ${inputPath}...`);
// Recurse over the files within this directory.
fs.readdir(inputPath, (err, items) => {
if (err) {
reject(err);
}
const promises: Promise<string>[] = items.map((item) => {
return this.readInputPath(inputPath + '/' + item);
});
Promise.all(promises).then((queryStrings: string[]) => {
resolve(queryStrings.reduce((x, y) => x + y, ''));
});
});
} else {
this.readInputFile(inputPath).then((result: string) => {
resolve(result);
}).catch((err) => {
console.log(`Error occurred in processing path ${inputPath}: `);
console.log(err.message);
reject(err);
});
}
});
});
}
// Takes a document and a query definition contained within that document. Then, extracts
// the fragments that the query depends on from the document and returns a document containing
// only those fragments.
public getQueryFragments(document: DocumentNode, queryDefinition: OperationDefinitionNode): DocumentNode {
const queryFragmentNames = getFragmentNames(queryDefinition.selectionSet, document);
const retDocument: DocumentNode = {
kind: 'Document',
definitions: [],
};
const reduceQueryDefinitions = (carry: FragmentDefinitionNode[], definition: DefinitionNode) => {
const definitionName = (definition as (FragmentDefinitionNode | OperationDefinitionNode)).name;
if ((isFragmentDefinition(definition) && queryFragmentNames[definitionName.value] === 1)) {
const definitionExists = carry.findIndex(
(value: FragmentDefinitionNode) => value.name.value === definitionName.value,
) !== -1;
// If this definition doesn't exist yet, add it.
if (!definitionExists) {
return [...carry, definition];
}
}
return carry;
};
retDocument.definitions = document.definitions.reduce(
reduceQueryDefinitions,
([] as FragmentDefinitionNode[]),
).sort(sortFragmentsByName);
return retDocument;
}
// Returns unique query ids.
public getQueryId() {
this.queryId += 1;
return this.queryId;
}
// Writes an OutputMap to a given file path.
public writeOutputMap(outputMap: OutputMap, outputFilePath: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.open(outputFilePath, 'w+', (openErr, fd) => {
if (openErr) { reject(openErr); }
fs.write(fd, JSON.stringify(outputMap), (writeErr, written, str) => {
if (writeErr) { reject(writeErr); }
resolve();
});
});
});
}
// Extracts GraphQL queries from this.inputFilePath and produces
// an output JSON file in this.outputFilePath.
public extract() {
this.processInputPath(this.inputFilePath).then((outputMap: OutputMap) => {
this.writeOutputMap(outputMap, this.outputFilePath).then(() => {
console.log(`Wrote output file to ${this.outputFilePath}.`);
}).catch((err) => {
console.log(`Unable to process ouput path ${this.outputFilePath}. Error message: `);
console.log(`${err.message}`);
});
}).catch((err) => {
console.log(`Unable to process input path ${this.inputFilePath}. Error message: `);
console.log(`${err.message}`);
});
}
}
// Type for the argument structure provided by the "yargs" library.
export interface YArgsv {
_: string[];
[ key: string ]: any;
}
// Main driving method for the command line tool
export const main = (argv: YArgsv) => {
// These are the unhypenated arguments that yargs does not process
// further.
const args: string[] = argv._;
let inputFilePath: string;
let outputFilePath: string;
const queryTransformers: QueryTransformer[] = [];
if (args.length < 1) {
console.log('Usage: persistgraphql input_file [output_file]');
} else if (args.length === 1) {
inputFilePath = args[0];
} else {
inputFilePath = args[0];
outputFilePath = args[1];
}
// Check if we are passed "--add_typename", if we are, we have to
// apply the typename query transformer.
if (argv['add_typename']) {
console.log('Using the add-typename query transformer.');
queryTransformers.push(addTypenameTransformer);
}
const options: ExtractGQLOptions = {
inputFilePath,
outputFilePath,
queryTransformers,
};
if (argv['js']) {
options.inJsCode = true;
}
if (argv['extension']) {
options.extension = argv['extension'];
}
new ExtractGQL(options).extract();
};