【问题标题】:How to pass variables into graphql-tag from node.js function?如何将变量从 node.js 函数传递到 graphql-tag?
【发布时间】:2020-03-24 04:31:56
【问题描述】:

我有以下功能:

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,而不是传递一个简单的标记文字作为查询。

【问题讨论】:

  • 如果您尝试将 $id 替换为类别 postsByCategory(id: ${category})

标签: javascript node.js graphql graphql-js


【解决方案1】:

您可以在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);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2016-10-25
    • 2017-08-10
    • 2018-04-07
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多