Jack
Jack

Reputation: 3057

Is it possible to use a variable for fields selection?

So I have this template function like so below.

I'd like to pass an email and some items get about that users email.

The $email variable works however I can't seem to get it to accept the second variable for the list of items.

const getUser = (email, items = ['email']) => ({
  query: `
    query ($email: String!, $items: [String]) {
      allUsers(condition:{ email: $email }) {
        edges {
          node {
            $items
          }
        }
      }
    }
  `,
  variables: {
    email,
    items,
  },
});

How can I dynamically pass a list of items for the query to return?

Upvotes: 0

Views: 41

Answers (2)

Daniel Rearden
Daniel Rearden

Reputation: 84677

The only way to translate variables into fields is using the @skip and @include directives. For example:

query MyQuery($image: Boolean!) {
  pokemons(first: 10) {
    name
    image @include(if: $image)
  }
}

Here the image field will only be included if the image variable is true, and skipped if the variable is false. The @skip directive works the same way but does the reverse. This is not sustainable for a large number of fields, but it's the only built-in way of doing what you're trying to achieve.

If you're able to modify the server code, then you could potentially create a custom directive that would work similarly, but would accept an array of string values and create a selection set from that list. A variable could then be passed to that custom directive. But again, that assumes you can modify the server-side code, which may not be the case.

Upvotes: 1

mab
mab

Reputation: 387

As the query itself is a (template)string, you may try like:

const getUser = (email, items = ['email']) => ({
  query: `
    query ($email: String!, $items: [String]) {
      allUsers(condition:{ email: $email }) {
        edges {
          node {
            ${items}
          }
        }
      }
    }
  `,
  variables: {
    email,
    items,
  },
});

Upvotes: 1

Related Questions