Extract operation name for better routing

16 views
Skip to first unread message

Ros

unread,
May 23, 2018, 1:02:17 PM5/23/18
to sangria-graphql
I have really large number of gql schemas, I want to make sure performance doesn't get hurt by scanning the schema after request is received. I have single endpoint.
So, I want to add routing based on the operation name. For that I need to extract the name of operation as defined in schema.

In my example below, I want to get the name of operation name (e.g. getUser) defined in schema field (query or mutation) and route it to respective schema for execution.

{
  "variables": {
    "id": "5b02cf7aaadd477013855334"
  },
  "query": "query MainAction($id: String!){getUser(id: $id){user{name, email}, ...}}"
}

I tried extract it after parsing the query using QueryParser.parse(query), but I couldn't extract the schema names.

Regards,
Ros

Oleg Ilyenko

unread,
May 23, 2018, 5:32:39 PM5/23/18
to sangria-graphql
If you would like to extract the root field names from the query, here is an example of how to do this:

import sangria.ast._
import sangria.parser._

val Success(query) = QueryParser.parse(
  """
    query MainAction($id: String!) {
      getUser(id: $id) {
        user {
          name
          email
        }
      }
    }
  """)
      
query.operation(Some("MainAction")).collect {
  case operation: OperationDefinition ⇒
    operation.selections.collect {
      case field: Field ⇒ field.name
    }
}

The result would be:

Some(Vector("getUser"))

Oleg Ilyenko

unread,
May 23, 2018, 5:36:41 PM5/23/18
to sangria-graphql
I also would like to mention that this kind of routing has some implication. For example, the query might contain the introspection fields (like `__type` or `__schema`) or it might have root field from different schemas in a single operation definition.
Reply all
Reply to author
Forward
0 new messages