Last active
August 9, 2022 18:20
-
-
Save cdelgadob/4041818430bc5802016332dbe5611570 to your computer and use it in GitHub Desktop.
This is a custom ApolloLink which we use to clean the "__typename" field to prevent sending it to the GraphQL server. omitDeep based on this gist: https://gist.github.com/Billy-/d94b65998501736bfe6521eadc1ab538
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cleanTypenameLink = new ApolloLink((operation, forward) => { | |
if (operation.variables) { | |
operation.variables = this.omitDeep (operation.variables, "__typename") | |
} | |
return forward(operation).map((data) => { | |
return data; | |
}) | |
}) | |
private omitDeep(obj, key) { | |
const keys = Object.keys(obj) | |
const newObj = {} | |
keys.forEach((i) => { | |
if (i !== key) { | |
const val = obj[i] | |
if (Array.isArray(val)) newObj[i] = this.omitDeepArrayWalk(val, key) | |
else if (typeof val === 'object' && val !== null) newObj[i] = this.omitDeep(val, key) | |
else newObj[i] = val | |
} | |
}) | |
return newObj | |
} | |
private omitDeepArrayWalk(arr, key) { | |
return arr.map((val) => { | |
if (Array.isArray(val)) return this.omitDeepArrayWalk(val, key) | |
else if (typeof val === 'object') return this.omitDeep(val, key) | |
return val | |
}) | |
} |
Hi @pedall,
In the init component I concatenate the Apollo links used in the app and composed them like this:
const myAppLink = ApolloLink.from ([
cleanTypenameLink,
resetTokenLink,
addTokenLink,
httpLink
])
this.apollo.create({
link: myAppLink,
cache: cache
})
Please let me know if this helps!
Carlos
Thanks for the snippet! I had to extend the omitDeep method to also let through Date objects, else they got stripped:
const omitDeep = (obj: object, key: string | number): object => {
const keys: Array<any> = Object.keys(obj);
const newObj: any = {};
keys.forEach((i: any) => {
if (i !== key) {
const val: any = obj[i];
if (val instanceof Date) newObj[i] = val;
else if (Array.isArray(val)) newObj[i] = omitDeepArrayWalk(val, key);
else if (typeof val === 'object' && val !== null) newObj[i] = omitDeep(val, key);
else newObj[i] = val;
}
});
return newObj;
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how do you integrate that ApolloLink in the ApolloClient?