/
WrapQuery.ts
74 lines (65 loc) · 2.2 KB
/
WrapQuery.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
import { FieldNode, visit, Kind, SelectionNode, SelectionSetNode } from 'graphql';
import { Transform, Request, ExecutionResult } from '@graphql-tools/utils';
export type QueryWrapper = (subtree: SelectionSetNode) => SelectionNode | SelectionSetNode;
export default class WrapQuery implements Transform {
private readonly wrapper: QueryWrapper;
private readonly extractor: (result: any) => any;
private readonly path: Array<string>;
constructor(path: Array<string>, wrapper: QueryWrapper, extractor: (result: any) => any) {
this.path = path;
this.wrapper = wrapper;
this.extractor = extractor;
}
public transformRequest(originalRequest: Request): Request {
const fieldPath: Array<string> = [];
const ourPath = JSON.stringify(this.path);
const document = visit(originalRequest.document, {
[Kind.FIELD]: {
enter: (node: FieldNode) => {
fieldPath.push(node.name.value);
if (ourPath === JSON.stringify(fieldPath)) {
const wrapResult = this.wrapper(node.selectionSet);
// Selection can be either a single selection or a selection set. If it's just one selection,
// let's wrap it in a selection set. Otherwise, keep it as is.
const selectionSet =
wrapResult != null && wrapResult.kind === Kind.SELECTION_SET
? wrapResult
: {
kind: Kind.SELECTION_SET,
selections: [wrapResult],
};
return {
...node,
selectionSet,
};
}
},
leave: () => {
fieldPath.pop();
},
},
});
return {
...originalRequest,
document,
};
}
public transformResult(originalResult: ExecutionResult): ExecutionResult {
const rootData = originalResult.data;
if (rootData != null) {
let data = rootData;
const path = [...this.path];
while (path.length > 1) {
const next = path.shift();
if (data[next]) {
data = data[next];
}
}
data[path[0]] = this.extractor(data[path[0]]);
}
return {
data: rootData,
errors: originalResult.errors,
};
}
}