Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables versus template literal interpolation

Are there any cases in which you should use ${foo} in your Apollo query instead of variables: {foo: foo}?

enter image description here

like image 874
Loren Avatar asked May 20 '16 02:05

Loren


1 Answers

You can do a lot with variables in a GraphQL query!

  • Obviously, you can pass variables as arguments to various fields
  • You can also use the @skip and @include directives to modify which fields are in the query

By combining these two tools and possibly others in the future, there's basically no need to do string interpolation.

Why is string interpolation in a GraphQL query bad? Well, for a few reasons it's best to think of a GraphQL query string as a static object, rather than a string to be manipulated:

  1. You could accidentally string-manipulate your way to an invalid query. If you don't properly escape some of the arguments, you could end up with a query that returns an error or some totally different data that you didn't expect. Variables are JSON-encoded, so there's no need to escape them.
  2. If your query is dynamically generated, there's no way to do static analysis on it using tools like eslint-plugin-graphql, so you can't check if your query is valid without actually running your code.
  3. It's going to be more difficult for other developers to understand what the shape of the returned data will be if a query is composed of many different strings. You also can't copy-paste the query into something like GraphiQL to try running it if there is arbitrary JavaScript code in there.

In short, there are tons of opportunities to do cool stuff with GraphQL query strings, but once you start manipulating them with arbitrary code that becomes much more difficult or impossible. So my suggestion is, stick to variables.

like image 108
stubailo Avatar answered Nov 15 '22 13:11

stubailo