gatsby-source-graphql
gatsby-source-graphql copied to clipboard
Any way to pass dynamic arguments
Hello!,
Im using this plugin to consume an external GraphQL server. In my graphQL server i have queries with Arguments. So in Gatsby i have for example my article.graphql file but i tried so many options for pass arguments without success.
# src/queries/article.graphql
{
article($nid: String!) {
nodeById(id: $id) {
id
title
body {
value
}
}
}
}
but doesn't works, can someone tell me the way to do this ?
If i do this with a hardcode value works:
# src/queries/article.graphql
{
nodeById(id: "1") {
id
title
body {
value
}
}
}
So in your config you would add a variables
option, like so:
// gatsby-config.js
{
resolve: '@wyze/gatsby-source-graphql',
options: {
url: 'https://api.graphql.local/',
variables: {
nid: 'n1',
id: 1
}
},
}
Let me know if that solves it for you. I think if you have more than 1 query the variables might be passed to all. I have #1 open that tries to solve that with having variables per query file.
Well if i need set Ids in the config, it isn't dynamic. Maybe i'm not understanding the concept of gatsby.
I have in my graphQL server queries to get By ID, and queries to get all articles. So in gatsby-node i created one script to make all pages for each article, but i need find the way to filter it. Because in the Article Template i have a GraphQL query to filter it By ID but doesn't work. Btw, thx.
Looks like this is the best I found: https://next.gatsbyjs.org/docs/graphql-reference/#query-variables
It mentions needing to use context when creating your page to pass in the query variables to the query to make it dynamic.
If the external GraphQL server runs Apollo, the way to pass parameters in a query is to define the options of "gatsby-source-graphql" in gatsby-config.js like this:
const { createHttpLink } = require(`apollo-link-http`)
const fetch = require(`node-fetch`)
<...>
{
resolve: "gatsby-source-graphql",
options: {
// Arbitrary name for the remote schema Query type
typeName: "MYTYPENAME",
// Field under which the remote schema will be accessible. You'll use this in your Gatsby query
fieldName: "myfieldname",
refetchInterval: 60,
// Url to query from
createLink: () =>
createHttpLink({
uri: "https://my-external-graphql-server.com/graphql",
headers: {
// Authorization: `bearer ${process.env.TOKEN}`, //optional Authorisation token
},
fetch,
})
},
}