How to find path to a field in a graphql query

1.8k Views Asked by At

I am very new to graphql. I have a following graphql query for an example:

query pets {
  breed(some arguments) 
  {
    name
    items 
    {
      owner(some arguments) 
      {
        items 
        {
          ID
          ownerSnumber
          country
          address
          school
          nationality
          gender
          activity
        }
      }
      name
      phoneNumber
      sin
    }
  }
}

Is it possible to parse a gql query and get the path of a field in the query? For example I would like to get the path of 'ID'. For example from the above query, is it possible to get the path where the ID is: owner.items.ID

2

There are 2 best solutions below

0
Sajeetharan On

With https://graphql.org/graphql-js/ it exposes a fourth argument called resolve info. This field contains more information about the field.

Have a look at GraphQLObjectType config parameter type definition:

0
Alan Bueno On

With a good start from the earlier answer, relying on the ResolveInfo you could do something like a recursive check going from child to parent:

export const getFieldPath = (path: Path): string => {
  if (!path.prev) return `${path.key}`

  return `${getFieldPath(path.prev)}.${path.key}`
}

And later in your resolver you could use it like:

const myFieldResolver = (parent, args, ctx, info) => {
  const pathOfThisResolversField = getFieldPath(info.path)

  // use your pathOfThisResolversField 

  return yourFieldResolvedData
};

Worth noting though, the solution above will include every node all the way to the query root, rather than just the ones you mentioned owner.items.ID