0

I'm practicing GQL, I've issue while displaying the data in Playground.

I trying to hit the jsonplaceholder api, to retrieve all posts and display them but it throws the following error.

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

Request:

{
  allPosts {
    id
  }
}

Response

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

Below is my Schema 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;
    });
  }

Note: I could able to see the results if I mock the response like below.

So if I hardcode the post data, then it works as expected, but not working when I hit from the API.

Please tell me what im doing wrong over here.

public postsData = [...]

  getAllPosts () {
    return this.postsData;
  }
nick
  • 1,310
  • 8
  • 15
Stzl
  • 65
  • 1
  • 7
  • If this code uses a library like `graphql-modules`, which it looks like it does, it would be worth mentioning in the question. – Daniel Rearden Jan 24 '19 at 13:02
  • I guess the question for me is what is `this.request`. It looks like it's using `fetch` under the hood, but if that's the case, why is your resolver getting the `body` property of the object returned by `response.json()`? – Daniel Rearden Jan 24 '19 at 13:04

1 Answers1

0

Daniel Rearden is right about the mention of using a fetch library. You need just more carefully take a look at the docs: https://developer.mozilla.org/en-US/docs/Web/API/Body/json

json() method returns Promise to JSON, not JSON itself, so you just need to resolve it first.

Also, as you're using async/await in query.ts it might be worth to keep the same approach of working with Promises and rewrite your 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;
  }
Yevhenii Herasymchuk
  • 2,047
  • 15
  • 20