Created
August 11, 2017 15:07
-
-
Save jonbretman/681b7483b39e4a1f23235634e5fceab7 to your computer and use it in GitHub Desktop.
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
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