如何从node.js函数将变量传递到graphql-tag?

我具有以下功能:

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')

但是我只是不明白如何将category变量传递给查询。我想在查询中使用qraphql-tag,而不要将简单的带标记文字作为查询。

wfsysysakk 回答:如何从node.js函数将变量传递到graphql-tag?

您可以在variables函数参数中使用client.query键,如下所示:

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);
};
本文链接:https://www.f2er.com/3013635.html

大家都在问