Skip to content

Instantly share code, notes, and snippets.

@RoryKelly
Created May 29, 2019 08:02
Show Gist options
  • Save RoryKelly/797c1b1e15e55a4956e2a943647e1de2 to your computer and use it in GitHub Desktop.
Save RoryKelly/797c1b1e15e55a4956e2a943647e1de2 to your computer and use it in GitHub Desktop.
Flatten graphql info using 'graphql-parse-resolve-info'
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(' ');
}
@RoryKelly
Copy link
Author

Can be used to turn Prisma types into Unions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment