【问题标题】:How to create a list of custom objects in GraphQL如何在 GraphQL 中创建自定义对象列表
【发布时间】:2015-11-16 23:09:08
【问题描述】:

我目前正在玩 Facebook 的一堆新技术。

我对 GraphQL 模式有一点问题。 我有这个对象模型:

{
        id: '1',
        participants: ['A', 'B'],
        messages: [
            {
                content: 'Hi there',
                sender: 'A'
            },
            {
                content: 'Hey! How are you doing?',
                sender: 'B'
            },
            {
                content: 'Pretty good and you?',
                sender: 'A'
            },
        ];
    }

现在我想为此创建一个 GraphQL 模型。我这样做了:

var theadType = new GraphQLObjectType({
  name: 'Thread',
  description: 'A Thread',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'id of the thread'
    },
    participants: {
      type: new GraphQLList(GraphQLString),
      description: 'Participants of thread'
    },
    messages: {
      type: new GraphQLList(),
      description: 'Messages in thread'
    }

  })
});

我知道首先有更优雅的方式来构建数据。但为了实验,我想这样尝试。

一切正常,除了我的消息数组,因为我没有指定数组类型。我必须指定进入该数组的数据类型。但由于它是一个自定义对象,我不知道将什么传递给 GraphQLList()。

除了为消息创建自己的类型之外,知道如何解决这个问题吗?

【问题讨论】:

    标签: javascript graphql


    【解决方案1】:

    我认为你不能在 GraphQL 中做到这一点。认为这有点违背 GraphQL 哲学,即在每个组件中要求“你需要”的字段而不是要求“全部”。

    当应用程序扩展时,您的方法会引发更多的数据负载。我知道为了测试这个库看起来有点太多了,但它似乎就是这样设计的。当前 GraphQL 库 (0.2.6) 中允许的类型有:

    • GraphQLSchema
    • GraphQLScalarType
    • GraphQLObjectType
    • GraphQLInterfaceType
    • GraphQLUnionType
    • GraphQLEnumType
    • GraphQLInputObjectType
    • GraphQLList
    • GraphQLNonNull
    • GraphQLInt
    • GraphQLFloat
    • GraphQLString
    • GraphQLBoolean
    • GraphQLID

    【讨论】:

    • 为什么投反对票?正如彼得希尔顿所说,您必须使用 GraphQLList 来实现您想要的,但您明确表示您不想要
    【解决方案2】:

    您可以像定义theadType 一样定义自己的自定义messageType,然后您可以使用new GraphQLList(messageType) 来指定消息列表的类型。

    【讨论】:

    • 感谢您的回复,我遇到了一个问题“..必须有一个子选择。”当我请求子元素时。你能举一个获取查询来获取消息的例子吗?
    猜你喜欢
    • 2017-04-24
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    相关资源
    最近更新 更多