Parse selectionSetGraphQL

Hi All,
I have a query with an interface as a return type.
To know which types were requested by the customer I’m trying, without a success, to parse selectionSetGraphQ.
Example:
‘{\n … on Dog {\n name\n color\n }\n name\n … on Cat {\n name\n type\n }\n … on Cow {\n birthday\n color\n }\n}’

do you have any idea how to parse the string mentioned above?

The graphql-js parse function will give you an AST. You can then use the visit function to traverse the AST and collect information from it.

I think this is what you want, but it should at least give you a good idea of where to go if not :slight_smile:

import { parse, visit } from 'graphql';

const ast = parse('...');
const concreteTypes = [];
visit(ast, {
  InlineFragment(node) {
    if (node.typeCondition) {
      concreteTypes.push(node.typeCondition.name.value);
    }
  }
});

Thank you for your response! Do you know if it’s also available in Python?

Hi @sapir_peer! You can do the same in Python using graphql-core’s parse function, like this:

import graphql

query = """
{
  animal {  
    ... on Dog {
      name
      color
    }
    name
    ... on Cat {
      name
      type
    }
    ... on Cow {
      birthday
      color
    }
  }
}
"""

parsed = graphql.parse(query)

print(parsed)

Are you using any library like Strawberry or Graphene? They already do this parsing so you might be able to get the information about the field selection inside the resolver (usually using a info parameter)

1 Like