【问题标题】:GraphQl array object inside object对象内的 GraphQl 数组对象
【发布时间】:2016-10-18 01:25:50
【问题描述】:

我从 api 进行 json 调用以获取帖子列表。我的问题是,在每个帖子对象响应中,我都有另一个用于帖子类别的对象数组。 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
    },
}),
});

谢谢

【问题讨论】:

  • 一般来说,如果有什么东西给你一个错误,你也应该发布错误是什么。它可以帮助其他人了解问题所在。
  • 我的错误信息是“[CatItem]”类型的字段“类别”必须有子选择

标签: reactjs graphql


【解决方案1】:

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

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

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

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

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

顺便说一句,有一个很棒的工具叫做 GraphiQL,它在开始编写查询时特别有用。你可能想看看中间件express-graphql

【讨论】:

  • 我尝试获取所有帖子,但在每个帖子中,我都有一个这样的每个类别的数组对象。
猜你喜欢
  • 2022-11-19
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 2018-11-21
相关资源
最近更新 更多