【问题标题】:GQL not returning resultsGQL 不返回结果
【发布时间】:2019-06-18 00:36:21
【问题描述】:

我正在练习 GQL,在 Playground 中显示数据时出现问题。

我试图点击 jsonplaceholder api,检索所有帖子并显示它们,但它会引发以下错误。

error: GRAPHQL_FORMAT_ERROR: Expected Iterable, but did not find one for field Query.allPosts.

请求:

{
  allPosts {
    id
  }
}

回应

{
      "errors": [
        {
          "extensions": {
            "code": "400"
          }
        }
      ],
      "data": {
        "allPosts": null
      }
    }

下面是我的架构Posts.graphql

#Description of Post

type Post {
  userId: Int
  id: Int
  title: String
  body: String
}

query.graphql

type Query {
  dangerousGoods: DangerousGoodsCIO
  allCourses: [Course]
  course(id: Int!): Course
  allPosts: [Post]
}

query.ts

export const Query: QueryResolvers.Resolvers = {
  async allPosts(_, _args, { injector }: ModuleContext) {
    const response = await injector.get(Api).getAllPosts();

    return response.body;
  }
};

api.ts

 getAllPosts() {
    const config = {
      uri: `https://jsonplaceholder.typicode.com/posts`,
      method: 'GET'
    };
    return this.request({ config, log: 'getAllPosts' })
    .then(response => {
      const allPost = response.json();
      return allPost;
    });
  }

注意:如果我像下面这样模拟响应,我可以看到结果。

因此,如果我对发布数据进行硬编码,那么它会按预期工作,但当我从 API 中点击时却无法正常工作。

请告诉我我在这里做错了什么。

public postsData = [...]

  getAllPosts () {
    return this.postsData;
  }

【问题讨论】:

  • 如果此代码使用像 graphql-modules 这样的库,看起来确实如此,那么值得在问题中提及。
  • 我想我的问题是this.request 是什么。看起来它在后台使用fetch,但如果是这种情况,为什么您的解析器会获取response.json() 返回的对象的body 属性?

标签: angular graphql apollo-client express-graphql


【解决方案1】:

Daniel Rearden 提到使用 fetch 库是对的。您需要更仔细地查看文档: https://developer.mozilla.org/en-US/docs/Web/API/Body/json

json() 方法返回 Promise 到 JSON,而不是 JSON 本身,所以你只需要先解决它。

此外,当您在 query.ts 中使用 async/await 时,可能值得保留使用 Promises 的相同方法并重写您的 api.ts

async getAllPosts() {
    const config = {
      uri: `https://jsonplaceholder.typicode.com/posts`,
      method: 'GET'
    };
    const response = await this.request({ config, log: 'getAllPosts' })
    const allPost = await response.json();
    return allPost;
  }

【讨论】:

  • 我收到此错误error: GRAPHQL_FORMAT_ERROR: response.json is not a function {"timestamp":"2019-01-28T05:30:15.065Z"}
  • 奇怪,你之前用 Promise 对象是怎么做到的?
猜你喜欢
  • 2015-04-23
  • 2018-01-09
  • 1970-01-01
  • 2014-06-05
  • 2020-04-05
  • 2018-03-19
  • 2011-07-17
  • 2015-09-29
  • 2013-03-12
相关资源
最近更新 更多