pasquers
pasquers

Reputation: 792

Use Graphql variables to define fields

I am trying to do something effectively like this

`query GetAllUsers($fields: [String]) {
    users {
        ...$fields
    }
}`

Where my client (currently Apollo for react) then passes in an array of fields in the variables section. The goal is to be able to pass in an array for what fields I want back, and that be interpolated to the appropriate graphql query. This currently returns a GraphQL Syntax error at $fields (expects a { but sees $ ). Is this even possible? Am I approaching this the wrong way?

One other option I had considered was invoking a JavaScript function and passing that result to query(), where the function would do something like the following:

buildQuery(fields) {
    return gql`
        query {
                users {
                    ${fields}
                }   
        }`
}

This however feels like an unecessary workaround.

Upvotes: 2

Views: 740

Answers (1)

xadm
xadm

Reputation: 8418

Comments summary:

Non standard requirements requires workarounds ;)

You can use fragments (for predefined fieldsets) but they probably won't be freely granular (field level).

Variables are definitely not for query definition (but for variables used in query).


Daniel's suggestion: gql-query-builder


It seams that graphQL community is great and full of people working on all possible use cases ... it's enough to search for solutions or ask on SO ;)

Upvotes: 2

Related Questions