/
Transformer.ts
45 lines (37 loc) · 1.58 KB
/
Transformer.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
import { Request, ExecutionResult } from '@graphql-tools/utils';
import { DelegationContext, DelegationBinding, Transform } from './types';
import { defaultDelegationBinding } from './delegationBindings';
interface Transformation {
transform: Transform;
context: Record<string, any>;
}
export class Transformer {
private transformations: Array<Transformation> = [];
private delegationContext: DelegationContext;
constructor(context: DelegationContext, binding: DelegationBinding = defaultDelegationBinding) {
this.delegationContext = context;
const delegationTransforms: Array<Transform> = binding(this.delegationContext);
delegationTransforms.forEach(transform => this.addTransform(transform, {}));
}
private addTransform(transform: Transform, context = {}) {
this.transformations.push({ transform, context });
}
public transformRequest(originalRequest: Request) {
return this.transformations.reduce(
(request: Request, transformation: Transformation) =>
transformation.transform.transformRequest != null
? transformation.transform.transformRequest(request, this.delegationContext, transformation.context)
: request,
originalRequest
);
}
public transformResult(originalResult: ExecutionResult) {
return this.transformations.reduceRight(
(result: ExecutionResult, transformation: Transformation) =>
transformation.transform.transformResult != null
? transformation.transform.transformResult(result, this.delegationContext, transformation.context)
: result,
originalResult
);
}
}