For example If I have some code like this:
import gql from 'graphql-tag'
const getUserMeta = /* GraphQL */ `
query GetUserMeta($owner: String!) {
getUserMeta(owner: $owner) {
familyName
givenName
workAddress
facebookUrl
owner
createdAt
updatedAt
careers {
items {
id
company
companyUrl
showCompany
owner
createdAt
updatedAt
}
nextToken
}
}
}
`;
const ast = gql(getUserMeta)
// for example if I want to remove the `showCompany` node
// I expect some method like this would work... but there is no such a method..
// ast.removeNodeByPath('GetUserMeta.careers.showCompany')
apolloClient.query(query:ast, variables: {limit: 100})
Have a look here: https://graphql.org/graphql-js/constructing-types/
The graphql-js
library provides the function to manipulate the AST.
I recommend using the visitor
function which is documented on that page.
Here is a snippet of code that use the visitor to add some stuff (just what I had as part of my product), it can give you a model to get started.
let editedAst = visit(stage.graphQLDocument, {
SelectionSet: {
leave(node, key, parent, path, ancestors) {
if (
ancestors.length === 5 &&
(ancestors[2] as OperationDefinitionNode).kind ===
'OperationDefinition' &&
(ancestors[3] as SelectionSetNode).kind === 'SelectionSet'
) {
if (
node.selections.find((s) => {
return (s as FieldNode).name.value === CHUNK_ID;
})
) {
return undefined;
}
const fieldChunkId = {
kind: 'Field',
directives: [],
name: { kind: 'Name', value: CHUNK_ID },
};
return {
...node,
selections: [...node.selections, fieldChunkId],
};
}
},
},