如何将变量从 node.js 函数传递到 graphql-tag?
How to pass variables into graphql-tag from node.js function?
我有以下功能:
import ApolloClient from 'apollo-boost'
import gql from 'graphql-tag'
import fetch from 'node-fetch'
global.fetch = fetch
const client = new ApolloClient({
uri: 'myUri'
})
const getPostsByCategory = async category => {
const res = await client.query({
query: gql`
query articlesByCategory($id: String!) {
postsByCategory(id: $id) {
id
}
}
`
})
console.log('res', res)
}
我想将函数调用为:
await getPostsByCategory('news')
但是我就是不明白我是如何将类别变量传递到查询中的。我想在我的查询中使用 qraphql-tag
而不是传递一个简单的标记文字作为查询。
您可以在 client.query
函数参数中使用 variables
键,如下所示
const getPostsByCategory = async category => {
const res = await client.query({
query: gql`
query articlesByCategory($id: String!) {
postsByCategory(id: $id) {
id
}
}
`,
variables: {
id: category,
},
});
console.log('res', res);
};
我有以下功能:
import ApolloClient from 'apollo-boost'
import gql from 'graphql-tag'
import fetch from 'node-fetch'
global.fetch = fetch
const client = new ApolloClient({
uri: 'myUri'
})
const getPostsByCategory = async category => {
const res = await client.query({
query: gql`
query articlesByCategory($id: String!) {
postsByCategory(id: $id) {
id
}
}
`
})
console.log('res', res)
}
我想将函数调用为:
await getPostsByCategory('news')
但是我就是不明白我是如何将类别变量传递到查询中的。我想在我的查询中使用 qraphql-tag
而不是传递一个简单的标记文字作为查询。
您可以在 client.query
函数参数中使用 variables
键,如下所示
const getPostsByCategory = async category => {
const res = await client.query({
query: gql`
query articlesByCategory($id: String!) {
postsByCategory(id: $id) {
id
}
}
`,
variables: {
id: category,
},
});
console.log('res', res);
};