Skip to content

Instantly share code, notes, and snippets.

@jonbretman
Created August 11, 2017 15:07
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 jonbretman/681b7483b39e4a1f23235634e5fceab7 to your computer and use it in GitHub Desktop.
Save jonbretman/681b7483b39e4a1f23235634e5fceab7 to your computer and use it in GitHub Desktop.
const graphql = require('graphql');
function getRequestedFields(query, info) {
const parsed = graphql.parse(query);
if (parsed.definitions.length > 1) {
throw new Error('Too many definitions');
}
const requested = info.operation;
let nodeA = parsed.definitions[0];
let nodeB = requested;
// eslint-disable-next-line no-constant-condition
while (true) {
if (nodeA.selectionSet && nodeA.selectionSet.selections.length > 1) {
throw new Error('Too many selections');
}
if (!nodeA.name) {
nodeA = nodeA.selectionSet.selections[0];
continue;
}
if (!nodeB.selectionSet) {
return [];
}
if (nodeA.name && nodeA.name.value === '__requestedFields') {
return nodeB.selectionSet.selections.map(x => x.name.value);
}
// eslint-disable-next-line no-loop-func
nodeB = nodeB.selectionSet.selections.find(x => {
return x.name.value === nodeA.name.value;
});
if (!nodeB) {
return [];
}
if (!nodeA.selectionSet) {
throw new Error('Missing __requestedFields field');
}
nodeA = nodeA.selectionSet.selections[0];
}
}
module.exports = getRequestedFields;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment