Created
May 29, 2019 08:02
-
-
Save RoryKelly/797c1b1e15e55a4956e2a943647e1de2 to your computer and use it in GitHub Desktop.
Flatten graphql info using 'graphql-parse-resolve-info'
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
import {FieldsByTypeName, parseResolveInfo, ResolveTree} from 'graphql-parse-resolve-info'; | |
const parsedResolveInfoFragment = parseResolveInfo(info) as ResolveTree; | |
const curation = await ctx.prismaBinding.query.curation( | |
{ | |
where: { | |
id: root.id, | |
}, | |
}, | |
` { id | |
content { | |
book { __typename ${flattenToString(parsedResolveInfoFragment.fieldsByTypeName.Book)} } | |
podcastEpisode { __typename ${flattenToString(parsedResolveInfoFragment.fieldsByTypeName.PodcastEpisode)} } | |
video { __typename ${flattenToString(parsedResolveInfoFragment.fieldsByTypeName.Video)} } | |
link { __typename ${flattenToString(parsedResolveInfoFragment.fieldsByTypeName.Link)} } | |
movie { __typename ${flattenToString(parsedResolveInfoFragment.fieldsByTypeName.Movie)} } | |
tvShow { __typename ${flattenToString(parsedResolveInfoFragment.fieldsByTypeName.TvShow)} } | |
} | |
}`, | |
); | |
const union = curation.content.podcastEpisode || | |
curation.content.video || | |
curation.content.link || | |
curation.content.movie || | |
curation.content.book || | |
curation.content.tvShow | |
function flattenToString(type: {[str: string]: ResolveTree}) { | |
// return empty for null t ype | |
if(!type) { | |
return '' | |
} | |
// loop through each field name | |
return Object.keys(type) | |
.map(value => type[value]) | |
.map(resolveTree => { | |
const alias = resolveTree.alias; | |
const typenameField = resolveTree.fieldsByTypeName; | |
const result = Object.keys(typenameField).map(typename => flattenToString(typenameField[typename])); | |
if (result.length > 0) { | |
return ` ${alias} { ${result.join(' ')} } `; | |
} else { | |
return ` ${alias} `; | |
} | |
}) | |
.join(' '); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can be used to turn Prisma types into Unions.