/
WrapConcreteTypes.ts
101 lines (87 loc) · 2.53 KB
/
WrapConcreteTypes.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import {
DocumentNode,
GraphQLSchema,
Kind,
getNamedType,
GraphQLOutputType,
isAbstractType,
TypeInfo,
visit,
visitWithTypeInfo,
isObjectType,
FieldNode,
} from 'graphql';
import { Request } from '@graphql-tools/utils';
import { Transform, DelegationContext } from '../types';
// For motivation, see https://github.com/ardatan/graphql-tools/issues/751
export default class WrapConcreteTypes implements Transform {
private readonly returnType: GraphQLOutputType;
private readonly targetSchema: GraphQLSchema;
constructor(returnType: GraphQLOutputType, targetSchema: GraphQLSchema) {
this.returnType = returnType;
this.targetSchema = targetSchema;
}
public transformRequest(
originalRequest: Request,
_delegationContext: DelegationContext,
_transformationContext: Record<string, any>
): Request {
const document = wrapConcreteTypes(this.returnType, this.targetSchema, originalRequest.document);
return {
...originalRequest,
document,
};
}
}
function wrapConcreteTypes(
returnType: GraphQLOutputType,
targetSchema: GraphQLSchema,
document: DocumentNode
): DocumentNode {
const namedType = getNamedType(returnType);
if (!isObjectType(namedType)) {
return document;
}
const queryRootType = targetSchema.getQueryType();
const mutationRootType = targetSchema.getMutationType();
const subscriptionRootType = targetSchema.getSubscriptionType();
const typeInfo = new TypeInfo(targetSchema);
const newDocument = visit(
document,
visitWithTypeInfo(typeInfo, {
[Kind.FIELD](node: FieldNode) {
const maybeType = typeInfo.getParentType();
if (maybeType == null) {
return false;
}
const parentType = getNamedType(maybeType);
if (parentType !== queryRootType && parentType !== mutationRootType && parentType !== subscriptionRootType) {
return false;
}
if (!isAbstractType(getNamedType(typeInfo.getType()))) {
return false;
}
return {
...node,
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [
{
kind: Kind.INLINE_FRAGMENT,
typeCondition: {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: namedType.name,
},
},
selectionSet: node.selectionSet,
},
],
},
};
},
})
);
return newDocument;
}