Skip to content

Instantly share code, notes, and snippets.

@jhancock532
Created January 4, 2024 15:41
Show Gist options
  • Save jhancock532/f951d1aa63dcceb94683a189e1698049 to your computer and use it in GitHub Desktop.
Save jhancock532/f951d1aa63dcceb94683a189e1698049 to your computer and use it in GitHub Desktop.
A custom GraphQL link for removing the __typename from the operation query object
// N.B. Consider disabling `addTypename` in InMemoryCache instead, if applicable
/*
const client = new ApolloClient({
...
cache: new InMemoryCache({
addTypename: false,
}),
...
});
*/
interface Name {
kind: string;
value: string;
}
interface Field {
kind: string;
name: Name;
}
interface SelectionSet {
selections?: (Field | SelectionSet)[];
[key: string]: any;
}
/**
* Recursively removes any "__typename" fields from "selections" arrays within "selectionSet" objects.
*
* @param data Any object (dict, list, etc.) to be processed.
* @returns A new object with the "__typename" fields removed.
*/
function removeTypeNameFields(data: any): any {
if (Array.isArray(data)) {
const newData: any[] = [];
for (const item of data) {
newData.push(removeTypeNameFields(item));
}
return newData;
}
if (typeof data === 'object') {
if (data.selectionSet) {
const newSelectionSet: SelectionSet = {};
for (const key in data.selectionSet) {
if (key !== 'selections') {
newSelectionSet[key] = removeTypeNameFields(data.selectionSet[key]);
}
}
const newSelections: (Field | SelectionSet)[] = [];
for (const item of data.selectionSet.selections || []) {
if (!(
typeof item === 'object' &&
item.kind === 'Field' &&
item.name &&
item.name.kind === 'Name' &&
item.name.value === '__typename'
)) {
newSelections.push(removeTypeNameFields(item) as Field);
}
}
data.selectionSet = newSelectionSet;
data.selectionSet.selections = newSelections;
}
return data;
}
return data;
}
const removeTypeNameLink = new ApolloLink((operation, forward) => {
const newDefinitions = removeTypeNameFields(operation.query.definitions);
const newQuery = {
...operation.query,
definitions: newDefinitions,
};
operation.query = newQuery;
return forward(operation).map((data) => data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment