GraphQl数组对象在对象内

时间:2016-10-16 21:39:22

标签: reactjs graphql

我从api做一个json调用来获取帖子列表。我的问题是,在每个post对象响应中,我有一个其他对象数组的帖子类别。如何使用Graphql获取数组对象类别?

我试试这个,但是给我回复错误

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
    },
}),
});

谢谢

1 个答案:

答案 0 :(得分:1)

您收到该消息是因为您必须告诉GraphQL要检索的categories中的哪些字段(子选择)。

您可能正在尝试运行类似这样的查询:

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

但您需要在categories上指定要返回的字段(子选择),如下所示:

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

顺便提一下,有一个很棒的工具叫做GraphiQL,在开始编写查询时特别有用。您可能需要查看中间件express-graphql