gig
gig

Reputation: 49

GraphQl array object inside object

I do a json call from a api to get a list of posts. My problem is that inside of every post object response, i have a other array of object for the category of the post. How can get the array object category using Graphql?

i try this but return me error

const Cat = new ObjectType({
name: 'CatItem',
description: 'cat',
fields: () => ({


    id: {
        type: new NonNull(ID),
        description: 'cat',
        resolve: (root) => root.id
    },
    slug: {
        type: StringType,
        description: 'cat',
        resolve: (root) => root.slug
    },
    name: {
        type: StringType,
        description: 'cat',
        resolve: (root) => root.name
    },


}),
});

const PostType = new ObjectType({
name: 'PostItem',
description: 'post',
fields: () => ({
    id: {
        type: new NonNull(ID),
        description: 'post',
        resolve: (root) => root.id
    },
    slug: {
        type: StringType,
        description: 'post',
        resolve: (root) => root.slug
    },
    title: {
        type: StringType,
        description: 'post',
        resolve: (root) => root.title
    },
    content: {
        type: StringType,
        description: 'post',
        resolve: (root) => root.content
    },
    categories: {
        type: new List(CatType),
        description: 'post',
        resolve: (root) => root.category
    },
    date: {
        type: StringType,
        description: 'post',
        resolve: (root) => root.date
    },
    authorName: {
        type: StringType,
        description: 'post',
        resolve: (root) => root.display_name
    },
    authorAvatar: {
        type: StringType,
        description: 'post',
        resolve: (root) => root.user_avatar
    },
}),
});

Thank you

Upvotes: 1

Views: 2786

Answers (1)

Eric Streeper
Eric Streeper

Reputation: 1154

You're getting that message because you have to tell GraphQL which fields (the subselection) within categories you want to retrieve.

You're probably trying to run a query something like this:

{
  post(id: 1) {
    title
    categories
  }
}

But you need to specify the fields to return (subselection) on categories, like the following:

{
  post(id: 1) {
    title
    categories {
      name
    }
  }
}  

Incidentally, there is a great tool called GraphiQL which is especially helpful when getting started writing queries. You might want to take a look at the middleware express-graphql.

Upvotes: 0

Related Questions