5

我正在尝试通过另一个 graphql API 的代理查询一个 graphql API 并且收到一个错误。我正在为我的服务器使用 graphql yoga 并从 CMS 连接到另一个 graphql API。这是我的代码:

服务器.js

const { GraphQLServer } = require('graphql-yoga');
const Prismic = require('./prismic.config.js');
const gql = require('graphql-tag');

const typeDefs = `
  type Query {
    page(lang: String, uid: String): Page
  }

  type Page {
    page_title: [TextField]
  }

  type TextField {
    text: String
  }
`

const resolvers = {
  Query: {
    page: (parent, args, context, info) => {
      const query = gql`${context.request.body.query}`;

      const result = context.Prismic.query({
        query,
        variables: { ...args }
      })
      .then(resp => {
        return resp.data.page;
      })
      .catch(err => console.log(err));
      return result;
    }
  }
}

const server = new GraphQLServer({ 
  typeDefs, 
  resolvers,
  context: req => ({ ...req, Prismic })
})

server.start(() => console.log('Server is running on localhost:4000'))

下面是我在 Graphql Yoga 附带的 graphql playground 上的查询:

query {
  page(lang: "en-gb", uid: "homepage") {
    page_title {
      text
    }
  }
}

我收到的错误是:

'查询未通过验证。违规:\n\n\'Json\' 类型的字段 \'page_title\' 不得有子选择。(第 3 行,第 5 列):\n page_title {\n ^' } },

奇怪的是,如果我在没有嵌套text字段的情况下对查询进行硬编码,因为服务器上的错误提示如下:

// const query = gql`${context.request.body.query}`;

const query = gql`
      query($uid: String!) {
        page(lang: "en-gb", uid: $uid) {
          page_title
        }
      }
    `;

尝试在 graphql 操场中修改我的查询以不包含嵌套text字段,如下所示:

query {
  page(lang: "en-gb", uid: "homepage") {
    page_title
  }
}

给我以下错误,根本不允许我提出请求:

“[TextField]”类型的字段“page_title”必须有一个子字段选择。您的意思是“page_title { ... }”吗?

该错误表明我需要添加text预期的嵌套子字段,但是当我使用此查询而不是服务器上的硬编码查询时,它会给我前面提到的错误。

不确定我的设置是否有问题?

谢谢

4

1 回答 1

2

In your GraphQL schema page_title: [TextField] is not one of the Scalar Types

As a result, during making a query you need to define what exactly fields you need to fetch? And your fields in the query should be expanded to the level of having only scalar types, so GraphQL will know how to resolve your query.

So this is the only query that should be from the first level (from graphql playground that comes with Graphql Yoga) :

query {
  page(lang: "en-gb", uid: "homepage") {
    page_title {
     text
    }
  }
}

But the error from the server throws from your approach to make graphql query inside graphql resolver:

const result = context.Prismic.query({
      query,
      variables: { ...args }
   })

So I'm 100% sure that the page_title in Prismic has the custom scalar - JSON. As a result, you can't use the same query for this request.

于 2018-12-10T14:13:58.297 回答