Skip to content

Instantly share code, notes, and snippets.

@Grohden
Created August 9, 2019 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grohden/1403a84f2b693f69797da9096accf62c to your computer and use it in GitHub Desktop.
Save Grohden/1403a84f2b693f69797da9096accf62c to your computer and use it in GitHub Desktop.
Fn to put deep __typename based on keys for apollo gql (apollo link rest is too verbose)
/*
* This is micro optimized, you could
* do it without mutability, but I think
* that this is to solve a very specific case (apollo
* requires __typename to be injected)
*/
function addTypeNames(
item: object,
typeNames: object
) {
const keys = Object.keys(item)
for(const key of keys) {
const typeName = typeNames[key]
const entry = item[key]
if(entry instanceof Array) {
entry.forEach(listEntry => addTypeNames({ [key]: listEntry }, typeNames))
continue
}
if(entry instanceof Object) {
if(typeName) {
entry.__typename = typeName
} else if(__DEV__) {
throw `'${key}' doesn't contain a key definition!`
} else {
// eslint-disable-next-line no-console
console.warn(`'${key}' doesn't contain a key definition!`)
}
addTypeNames(entry, typeNames)
}
}
}
const myReturn = {
entry: {
deepProp:{
foo: 2
}
}
}
addTypeNames({ root: myReturn }, {
root: 'RootType'
entry: 'EntryType'
deepProp: 'DeepProp'
})
console.log(myReturn)
/* ->
{
__typename: 'RootType'
entry: {
__typename: 'EntryType'
deepProp:{
__typename: 'DeepProp'
foo: 2
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment