如何在 GraphQL 中创建自定义对象列表

How to create a list of custom objects in GraphQL

我最近在玩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()。

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

我不认为你可以在 GraphQL 中做到这一点。认为在每个组件中请求字段 "you need" 而不是请求 "them all" 有点违背 GraphQL 哲学。

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

  • GraphQLSchema
  • GraphQLScalarType
  • GraphQLObjectType
  • GraphQLInterfaceType
  • GraphQLUnionType
  • GraphQLEnumType
  • GraphQLInputObjectType
  • GraphQLList
  • GraphQLNonNull
  • GraphQLInt
  • GraphQLFloat
  • GraphQLString
  • GraphQL布尔值
  • GraphQLID

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