Skip to content

Instantly share code, notes, and snippets.

@RAMPKORV
Created September 9, 2020 19:47
Show Gist options
  • Select an option

  • Save RAMPKORV/901b043212a6595abdd3764c96869893 to your computer and use it in GitHub Desktop.

Select an option

Save RAMPKORV/901b043212a6595abdd3764c96869893 to your computer and use it in GitHub Desktop.
Parse ASTInfo to determine which of a set of GraphQL fields that have been requested
/* Given a list of fields, such as [ 'a', 'b', 'c' ] and ASTInfo, return an object
on the form {a: true, b: false, c: true } where a property is true if the field is requested through the ASTInfo */
const getRequestedFields = (fieldNames, info) => {
let { fieldNodes, fragments } = info;
let result = {};
for (let i = 0; i < fieldNodes.length; i++) {
if (!fieldNodes[i].selectionSet) {
continue;
}
for (let j = 0; j < fieldNodes[i].selectionSet.selections.length; j++) {
if (fieldNodes[i].selectionSet.selections[j].kind === "InlineFragment") {
result = {
...result,
...getRequestedFields(fieldNames, {
fieldNodes: fieldNodes[i].selectionSet.selections,
fragments,
}),
};
} else if (
fieldNodes[i].selectionSet.selections[j].kind === "FragmentSpread"
) {
let fragmentName = fieldNodes[i].selectionSet.selections[j].name.value;
result = {
...result,
...getRequestedFields(fieldNames, {
fieldNodes: [fragments[fragmentName]],
fragments,
}),
};
}
for (let k = 0; k < fieldNames.length; k++) {
if (
fieldNodes[i].selectionSet.selections[j].kind === "Field" &&
fieldNodes[i].selectionSet.selections[j].name.value === fieldNames[k]
) {
result[fieldNames[k]] = true;
fieldNames.splice(k, 1);
if (fieldNames.length === 0) {
return result;
}
break;
}
}
}
}
for (let i = 0; i < fieldNames.length; i++) {
result[fieldNames[i]] = false;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment