Graphql-tag: Parse variables

Created on 24 Oct 2017  路  7Comments  路  Source: apollographql/graphql-tag

It would be great if this could also parse variable definitions included.

e.g.

query ProjectLists($defaultCount: Int!) {
  projectList(count: $defaultCount) {
    id
    name
  }
}

variables {
  "defaultCount": 50
}

With the AST that graphql-tag provides, it should be easy to convert this into an applicable request body. Is there any other solution/package that i'm unaware of that allows me to do this?

Most helpful comment

After hours of going through unclear documentation, this works for us at Aloha Health Network

import {ApolloProvider, Query, graphql} from 'react-apollo'
import {ApolloClient, HttpLink, InMemoryCache} from 'apollo-boost'
import gql from 'graphql-tag'

module.exports = React.createClass({
  render: function() {
    /*
     * Retrieve user's matched clinical trials
     */
    const matrixUserId = MatrixClientPeg.get().credentials.userId

    // console.log(`Matrix userid: ${matrixUserId}`);

    const queryUserVariable = {
      "matrixUserId": matrixUserId
    }

    const apolloClient = new ApolloClient({
      link: new HttpLink({uri: this.props.alohaTenantAPI}),
      cache: new InMemoryCache(),
    })

    const ClinicalTrialQuery = gql`
      query ($matrixUserId: String!) {
        user(userId: $matrixUserId) {
          matched_trials {
            trial {
              id
              public_title
              brief_summary
              status
              study_phase
              locations {
                name
              }
            }
          }
        }
      }
    `

    const AlohaClinicalTrialListWithData = graphql(ClinicalTrialQuery, {
      name: 'ClinicalTrialData',
      options: { variables: queryUserVariable }
    })(AlohaClinicalTrialList)

    return (
      <div className="aloha-matched-list-view clearfix">
        <h2 className="clearfix">My Clinical Trial List</h2>
        <ApolloProvider client={apolloClient}>
          <AlohaClinicalTrialListWithData />
        </ApolloProvider>
      </div>
    )
  },
})

All 7 comments

Majorly seconded. I've been trying to follow documentation for 2.0.0 and they all tell me to use graphql-tag. However, variable usage is completely unavailable.

Does anyone know about how to use gql (using graphgql-tag) with variables and options. The documentation is here which I have been following.
My code:

const currentUserEnv = gql`
query{
  environments($identityId: String!){
    uuid
    imageLink
    title
  }
}`;
const envWithData = graphql(currentUserEnv, {
  options: { variables: { identityId: 'user-id' } }
})(Dashboard);
export default envWithData;

Error:
image

@shahzeb1 this section of the GraphQL documentation should explain variables fairly thoroughly: http://graphql.org/learn/queries/#variables

in short, you're missing the variable declaration following the query keyword, i.e.,

query($identityId: String!) {
  environments(identityId: $identityId)
}

@codepunkt im not aware of anything that can do what you're looking for. the solution you provide would require changing the GraphQL specification itself (since the AST we're parsing with graphql-tag is just using the GraphQL parser).

you can, however, define default values for variables: http://graphql.org/learn/queries/#default-variables. e.g.,

query HeroNameAndFriends($episode: Episode = "JEDI") {
  hero(episode: $episode) {
    name
    friends {
      name
    }
  }
}

closing this for now since graphql-tag is subject to the graphql parser's rules

@jnwng awesome, thank you!

@jnwng thanks for the quick feedback. that's a pity! 馃槩

just to be on the same page - you're talking about the graphql/graphql-js parser? i've always thought of variables as part of the graphql query language and specification so i'm kind of confused why those would not be parsed.

@jnwng thanks, I was confused like @codepunkt

After hours of going through unclear documentation, this works for us at Aloha Health Network

import {ApolloProvider, Query, graphql} from 'react-apollo'
import {ApolloClient, HttpLink, InMemoryCache} from 'apollo-boost'
import gql from 'graphql-tag'

module.exports = React.createClass({
  render: function() {
    /*
     * Retrieve user's matched clinical trials
     */
    const matrixUserId = MatrixClientPeg.get().credentials.userId

    // console.log(`Matrix userid: ${matrixUserId}`);

    const queryUserVariable = {
      "matrixUserId": matrixUserId
    }

    const apolloClient = new ApolloClient({
      link: new HttpLink({uri: this.props.alohaTenantAPI}),
      cache: new InMemoryCache(),
    })

    const ClinicalTrialQuery = gql`
      query ($matrixUserId: String!) {
        user(userId: $matrixUserId) {
          matched_trials {
            trial {
              id
              public_title
              brief_summary
              status
              study_phase
              locations {
                name
              }
            }
          }
        }
      }
    `

    const AlohaClinicalTrialListWithData = graphql(ClinicalTrialQuery, {
      name: 'ClinicalTrialData',
      options: { variables: queryUserVariable }
    })(AlohaClinicalTrialList)

    return (
      <div className="aloha-matched-list-view clearfix">
        <h2 className="clearfix">My Clinical Trial List</h2>
        <ApolloProvider client={apolloClient}>
          <AlohaClinicalTrialListWithData />
        </ApolloProvider>
      </div>
    )
  },
})
Was this page helpful?
0 / 5 - 0 ratings