-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
add-typename-selection-document-transform.ts
38 lines (37 loc) · 1.24 KB
/
add-typename-selection-document-transform.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
import { Kind, visit } from 'graphql';
import { Types } from '@graphql-codegen/plugin-helpers';
/**
* Automatically adds `__typename` selections to every object type in your GraphQL document.
* This is useful for GraphQL Clients such as Apollo Client or urql that need typename information for their cache to function.
*/
export const addTypenameSelectionDocumentTransform: Types.DocumentTransformObject = {
transform({ documents }) {
return documents.map(document => ({
...document,
document: document.document
? visit(document.document, {
SelectionSet(node) {
if (
!node.selections.find(selection => selection.kind === 'Field' && selection.name.value === '__typename')
) {
return {
...node,
selections: [
{
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: '__typename',
},
},
...node.selections,
],
};
}
return undefined;
},
})
: undefined,
}));
},
};