Created
August 9, 2019 03:06
-
-
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 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
/* | |
* 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