-
-
Notifications
You must be signed in to change notification settings - Fork 801
/
ExtractField.ts
65 lines (59 loc) · 1.87 KB
/
ExtractField.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
import { BREAK, FieldNode, Kind, SelectionSetNode, visit } from 'graphql';
import { DelegationContext, Transform } from '@graphql-tools/delegate';
import { ExecutionRequest } from '@graphql-tools/utils';
interface ExtractFieldTransformationContext extends Record<string, any> {}
export default class ExtractField<TContext = Record<string, any>>
implements Transform<ExtractFieldTransformationContext, TContext>
{
private readonly from: Array<string>;
private readonly to: Array<string>;
constructor({ from, to }: { from: Array<string>; to: Array<string> }) {
this.from = from;
this.to = to;
}
public transformRequest(
originalRequest: ExecutionRequest,
_delegationContext: DelegationContext<TContext>,
_transformationContext: ExtractFieldTransformationContext,
): ExecutionRequest {
let fromSelection: SelectionSetNode | undefined;
const ourPathFrom = JSON.stringify(this.from);
const ourPathTo = JSON.stringify(this.to);
let fieldPath: Array<string> = [];
visit(originalRequest.document, {
[Kind.FIELD]: {
enter: (node: FieldNode) => {
fieldPath.push(node.name.value);
if (ourPathFrom === JSON.stringify(fieldPath)) {
fromSelection = node.selectionSet;
return BREAK;
}
},
leave: () => {
fieldPath.pop();
},
},
});
fieldPath = [];
const document = visit(originalRequest.document, {
[Kind.FIELD]: {
enter: (node: FieldNode) => {
fieldPath.push(node.name.value);
if (ourPathTo === JSON.stringify(fieldPath) && fromSelection != null) {
return {
...node,
selectionSet: fromSelection,
};
}
},
leave: () => {
fieldPath.pop();
},
},
});
return {
...originalRequest,
document,
};
}
}