GQL 不返回结果



我正在练习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]
}

查询.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;
  }

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

json()方法将 Promise 返回给 JSON,而不是 JSON 本身,因此您只需要先解决它。

此外,由于您在query.ts中使用 async/await,因此可能值得保持与 Promise 相同的方法并重写您的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;
  }

最新更新