/
utils.ts
85 lines (70 loc) · 2.48 KB
/
utils.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
import { parse, dirname, relative, join, isAbsolute } from 'path';
import { DocumentNode, visit, FragmentSpreadNode, FragmentDefinitionNode, FieldNode, Kind } from 'graphql';
import { FragmentNameToFile } from './index';
export function appendExtensionToFilePath(baseFilePath: string, extension: string) {
const parsedPath = parse(baseFilePath);
return join(parsedPath.dir, parsedPath.name + extension).replace(/\\/g, '/');
}
export function clearExtension(path: string): string {
const parsedPath = parse(path);
return join(parsedPath.dir, parsedPath.name).replace(/\\/g, '/');
}
export function extractExternalFragmentsInUse(
documentNode: DocumentNode | FragmentDefinitionNode,
fragmentNameToFile: FragmentNameToFile,
result: { [fragmentName: string]: number } = {},
ignoreList: Set<string> = new Set(),
level = 0
): { [fragmentName: string]: number } {
// First, take all fragments definition from the current file, and mark them as ignored
visit(documentNode, {
enter: {
FragmentDefinition: (node: FragmentDefinitionNode) => {
ignoreList.add(node.name.value);
},
},
});
// Then, look for all used fragments in this document
visit(documentNode, {
enter: {
FragmentSpread: (node: FragmentSpreadNode) => {
if (!ignoreList.has(node.name.value)) {
result[node.name.value] = level;
if (fragmentNameToFile[node.name.value]) {
extractExternalFragmentsInUse(fragmentNameToFile[node.name.value].node, fragmentNameToFile, result, ignoreList, level + 1);
}
}
},
},
});
return result;
}
export function fixLocalFile(path: string): string {
if (!path.startsWith('..')) {
return `./${path}`;
}
return path;
}
export function resolveRelativeImport(from: string, to: string): string {
if (!isAbsolute(from)) {
throw new Error(`Argument 'from' must be an absolute path, '${from}' given.`);
}
if (!isAbsolute(to)) {
throw new Error(`Argument 'to' must be an absolute path, '${to}' given.`);
}
return fixLocalFile(clearExtension(relative(dirname(from), to)));
}
export function isUsingTypes(document: DocumentNode): boolean {
let foundFields = 0;
visit(document, {
enter: {
Field: (node: FieldNode) => {
const selections = node.selectionSet ? node.selectionSet.selections || [] : [];
if (selections.length === 0 || selections[0].kind === Kind.FRAGMENT_SPREAD) {
foundFields++;
}
},
},
});
return foundFields > 0;
}