javascriptgraphqlaxiosgraphql-tag

Import graphql query .gql file into plain Javascript and run an axios call


I have a simple axios call that I want to make to fetch some graphql data. I also have a .gql file that I want to import to use as a query:

pages.gql

{
  entries(section: [pages]) {
    uri
    slug
  }
}

Now in my other file I want to import that:

import query from './queries/pages.gql'

To later make that axios call:

const routes = await axios.post(
    endpoint,
    { query },
    { headers: { Authorization: `Bearer ${token}` } }
  )
  .then(result => {
    console.log('result: ', result)
  })
  .catch(error => {
    console.log('error: ', error)
  })

But whenever I do that I will get this error:

missing ) after argument list 09:55:25

entries(section: [pages]) {

^^^^^^^

SyntaxError: missing ) after argument list

So I can't just import the gql file. I have graphql-tag imported (import gql from 'graphql-tag'), so I could do something like this:

const QUERY = gql`
  ${query}
`

but first I have to import the gql file, right?

Any help would be much appreciated... cheers

---- Edit 2019-08-28: ----

OK, another case:

I have an axios call that works like a charm:

await axios
    .post(
      endpoint,
      { query: `query Page($slug: String!) {
          entries(section: [pages], slug: $slug) {
            slug
            title
          }
        }`,
        variables: { slug: params.slug }
      },
      { headers: { Authorization: `Bearer ${env.GRAPHQL_TOKEN}` } }
    ).then(result => {
      console.log('result: ', result)
    })
    .catch(error => {
      console.log('error: ', error)
    })

I also have a page.gql file with the exact same content:

query Page($slug: String!) {
  entries(section: [pages], slug: $slug) {
    slug
    title
  }
}

I found out that importing the page.gql file like this import page from '~/apollo/queries/page' Would import something of this structure:

    page:  {                                                                                                                                         15:16:40
        kind: 'Document',
        definitions: [...],
        loc: {
            start: 0,
            end: 181,
            source: {
            body: 'query Page($slug: String!) {\n  ' +
                'entries(section: [pages], slug: $slug) {\n    ' +
                'slug\n    title\n   }\n  }\n}\n',
            name: 'GraphQL request',
            locationOffset: [Object]
            }
        },
        Page: {...}
    }

So to use the page.gql in my query I have to use this page.loc.source.body:

  await axios
    .post(
      endpoint,
      { query: page.loc.source.body,
        variables: { slug: params.slug }
      },
      { headers: { Authorization: `Bearer ${env.GRAPHQL_TOKEN}` } }
    ).then(result => {
      console.log('result: ', result)
    })
    .catch(error => {
      console.log('error: ', error)
    })

Is there a better way than this?


Solution

  • The graphql tag template literal(gql`..`) parses the graphql query to an AST (abstract syntax tree; further reading: https://www.contentful.com/blog/2018/07/04/graphql-abstract-syntax-tree-new-schema/). The advantage of parsing to an AST (on the client-side) is that it allows you to lint your queries and eases query handling e.g. with fragments (see: https://github.com/apollographql/graphql-tag#why-use-this)

    If you want to pass your query to axios/fetch, you'll need to parse it back to a an actual query string using the graphql printer fn (https://graphql.org/graphql-js/language/#printer):

    import gql from 'graphql-tag';
    import { print } from 'graphql/language/printer';
    
    const AST = gql`
      {
        user(id: 5) {
          firstName
          lastName
        }
      }
    `
    const query = print(AST);