Created
May 15, 2023 08:52
-
-
Save rjanjic/13c45cce65191f21fe904c571d02add4 to your computer and use it in GitHub Desktop.
Recursively remove __typename properties from a GraphQL response.
This file contains hidden or 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
/** | |
* Recursively remove __typename properties from a GraphQL response. | |
* | |
* @param response The GraphQL response object. | |
* @return The cleaned response object. | |
*/ | |
function stripTypename(response: any): any { | |
if (Array.isArray(response)) { | |
return response.map(stripTypename); | |
} | |
if (typeof response === 'object' && response !== null) { | |
return Object.fromEntries( | |
Object.entries(response) | |
.filter(([key]) => key !== '__typename') | |
.map(([key, value]) => [key, stripTypename(value)]), | |
); | |
} | |
return response; | |
} | |
const response = { | |
data: { | |
__typename: 'Query', | |
user: { | |
__typename: 'User', | |
id: '1', | |
name: 'John Doe', | |
posts: [ | |
{ | |
__typename: 'Post', | |
id: '1', | |
title: 'First post', | |
}, | |
{ | |
__typename: 'Post', | |
id: '2', | |
title: 'Second post', | |
}, | |
], | |
}, | |
}, | |
}; | |
console.log(stripTypename(response)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment