Hi there.
I assume this could be a noob question, but I did not find any help on the web and nor did I find any working examples somewhere here.
I am trying to run an axios request to a graphql service.
This by itself works pretty nice:
await axios
.post(
endpoint,
{ query: `{ entries (section: [pages]) { uri } }` },
{ headers: { Authorization: `Bearer ${token}` } }
)
.then(result => {
console.log('result: ', result) // eslint-disable-line
})
then I started to put my graphql query into a .gql file.
I then had to make the request like this:
import query from '~/apollo/queries/query'
await axios
.post(
endpoint,
{ query: query.loc.source.body, },
{ headers: { Authorization: `Bearer ${token}` } }
)
.then(result => {
console.log('result: ', result) // eslint-disable-line
})
Probably not the way to go, but I did not find any other solution.
In the meantime I changed the query.gql and added fragments into it:
#import "./fragments/heroBuilder.gql"
#import "./fragments/pageBuilder.gql"
query Page($slug: String!) {
entries(section: [pages, pagesInSmallNavigation], slug: $slug) {
slug
title
... on Pages {
heroBuilder {
...heroFragment
...introImageFragment
}
alternativePageTitle
pageBuilder {
...pageBuilderFragment
...highlightsFragment
}
}
}
}
And since then I get an error when making the axios call and it says
[ { message: 'Unknown fragment "heroFragment".',
category: 'graphql',
locations: [ [Object] ] },
{ message: 'Unknown fragment "introImageFragment".',
category: 'graphql',
locations: [ [Object] ] },
{ message: 'Unknown fragment "pageBuilderFragment".',
category: 'graphql',
locations: [ [Object] ] },
{ message: 'Unknown fragment "highlightsFragment".',
category: 'graphql',
locations: [ [Object] ] } ]
So I assume that the imports don't really work.
I tried to get it to work with
import gql from 'graphql-tag and then wrap my query into it, but no success so far.
Could someone share an example how to use .gql files together with fragments and axios?
That would be very much appreciated...
Thank you in advance.
cheers
@Jones-S I've been searching for a solution to this as well. query.loc.source.body is definitely not going to work for complex ASTs. The imports _are_ working, but you need to properly convert the AST object back to a string. You can use the graphql reference library to do this.
import { query } from 'yourQuery.gql';
import { print } from 'graphql/language/printer';
let queryString = print(query);
// POST { query: queryString } via axios to your endpoint
Good luck!
Yes, thank you. I know already :). Sorry I forgot that I should have reported back to this issue:
https://stackoverflow.com/a/57873339/1121268
Most helpful comment
@Jones-S I've been searching for a solution to this as well.
query.loc.source.bodyis definitely not going to work for complex ASTs. The imports _are_ working, but you need to properly convert the AST object back to a string. You can use the graphql reference library to do this.Good luck!