2

I have this query defined, and use it succesfully in my app:

export const GET_TEAM = gql`
  query($id: ID!) {
    getTeam(id: $id) {
      ...CompleteTeam
    }
  }
  ${fragments.team}
`

But would like to use it for mocking purpose, and for that I need this representation:

getTeam(id: 3) {
  id
  name
  isActivated
}

Is there any easy way to call gql with variables to accomplish?

There are suggestions how to do this with an instance of ApolloClient. But if possible I'd rather skip involvning the client as I will only mock the resulting data.

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • The GQL function returns a GraphQL Document that can be printed using GraphQL.js. [See this discussion in Github](https://github.com/apollographql/graphql-tag/issues/144#issuecomment-360861636) – Herku Nov 17 '18 at 13:30
  • Interesting! Any idea how that could be used to query with variables? – Fellow Stranger Nov 17 '18 at 14:06
  • AST Document provide the original string under `GET_TEAM.loc.source.body` – ManUtopiK Mar 09 '21 at 00:37
  • @FellowStranger were you able to figure out an easier solution to your question yet? If yes, please do share :) – Eesa Aug 24 '21 at 14:53

1 Answers1

0

To follow up a bit here: The gql function returns a GraphQL Document AST (a parsed tree representation of the query). ASTs are much easier to work with than strings - at least when it gets more complicated.

For your question in the comment: Once you are in the AST space you can do all sorts of transforms. This can be done for example using the visitor patter. GraphQL.js also comes with a visit function that allows you to replace nodes. This code should serve as inspiration, no guarantees that it works ;)

function valueToNode(value) {
  if (typeof value === 'string') {
    return { kind: 'StringValue', value };
  } else if (typeof value === 'number' && Number.isInteger(value)) {
    // return integer value node
  }
  // all other value nodes...
}

visit(ast, {
  VariableNode: {
    enter(node) {
      return valueToNode(variables[node.name.value]);
    }
  }
}

I am not sure if you should leave the AST space but as described in the comment you can use the printer as mentioned in the comment. Not sure if it prints things that are not documents.

Herku
  • 7,198
  • 27
  • 36