-
Notifications
You must be signed in to change notification settings - Fork 26
/
utility-functions.ts
58 lines (54 loc) · 1.73 KB
/
utility-functions.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
import type { DocumentNode, FragmentDefinitionNode } from 'graphql';
export function getFragmentsInDocument(...documentNodes: (DocumentNode | undefined)[]) {
const fragmentDefs = new Map<string, FragmentDefinitionNode>();
for (const documentNode of documentNodes) {
if (!documentNode) return [];
for (const def of documentNode.definitions) {
if (def.kind === 'FragmentDefinition') {
fragmentDefs.set(def.name.value, def);
}
}
}
return [...fragmentDefs.values()];
}
export function getFragmentNamesInDocument(...documentNodes: (DocumentNode | undefined)[]) {
const nameSet = new Set<string>();
for (const documentNode of documentNodes) {
if (!documentNode) return [];
for (const def of documentNode.definitions) {
if (def.kind === 'FragmentDefinition') {
nameSet.add(def.name.value);
}
}
}
return [...nameSet];
}
export function cloneFragmentMap(from: Map<string, FragmentDefinitionNode>, namesToBeExcluded: string[] = []) {
const map = new Map(from);
for (const name in namesToBeExcluded) {
map.delete(name);
}
return map;
}
export function detectDuplicatedFragments(documentNode: DocumentNode) {
const fragments: FragmentDefinitionNode[] = [];
const duplicatedFragments: FragmentDefinitionNode[] = [];
documentNode.definitions.forEach(def => {
if (def.kind === 'FragmentDefinition') {
if (fragments.some(f => f.name.value === def.name.value)) {
duplicatedFragments.push(def);
} else {
fragments.push(def);
}
}
});
return duplicatedFragments
.map(def => {
return {
name: def.name.value,
start: def.loc!.start,
end: def.loc!.end,
};
})
.sort((a, b) => b.start - a.start);
}