GraphQL:如何实现 GraphQLObjectTypes 的 GraphQLList

GraphQL: How to implement a GraphQLList of GraphQLObjectTypes

我对 GraphQL 有疑问(特别是实现 GraphQLList)

我有一个查询 getItemByName,它正确地 return 是一个 Item,类型为 itemType。但是我还没有能够实现 getItemList (或者顺便说一句适当的例子)。我知道它应该有一个实现 GraphQLList 的类型。

但我做对了吗? resolve 应该接收的数据格式是什么? (或者 getItems() 应该 return)。对象数组?这些对象应该执行 "itemType" 定义吗?是否应该实现接口?

export const itemType = new GraphQLObjectType({
  name: 'Item',
  fields: {
    name: {
      type: GraphQLString,
      description: 'Item Name',
    },
  },
});

const itemListType = new GraphQLObjectType({
  name: 'ItemsList',
  fields: {
    items: {
      type: new GraphQLList(itemType),
      description: 'List of items',
    },
  },
});

{...}

const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'Query',
        fields: {
           itemList: {
               type: itemListType,
               resolve: () => getItems(),
           }
        }
    })
})

现在查询:

itemList {
  items {
    name
  }
}

它的 returning:

{
  "data": {
    "itemList": {
      "items": null
    }
  }
}

非常欢迎任何帮助! :D

此致!

getItems() 应该 return 一组 itemType 对象(或一个对象的承诺)。这些 itemType 的外观取决于您。它们将简单地传递给您在 itemType.

中要求的字段的 resolve 函数

已解决问题。 这不是我返回的数据结构的问题,而是我定义查询的方式。

export const coworkList = {
  name: 'coworkList',
  description: 'Returns a list (up until 10) of coworks',
  type:  new GraphQLList(coworkType),
  resolve: () => getCoworks(),
};

coworkList查询定义现在正在传递到架构中。 效果很好! const schema = new GraphQL

Schema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: () => ({
      coworkList,
      coworkByName,
      coworkById,
    }),
  }),
});

我先解释一下你的问题的根本原因。然后再说说GraphQLList一般是怎么用的

在您的架构查询中,itemList 字段的类型为 itemListType。现在这个 itemListType 有一个字段 items。因此,查询的 itemList 字段必须解析为具有 items 字段的对象。但是 getItems() 函数 returns 一个数组或一个承诺的数组并且没有字段 items。这就是您在查询响应中得到 "items": null 的原因。

现在关于 GraphQLList 的混淆:如果它只是一个列表,实际上没有必要为此定义单独的 GraphQL 类型。在您的查询中,您包含一个项目类型为 GraphQLList 的字段:

const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'Query',
        fields: {
           itemList: {
               type: new GraphQLList(itemType),
               resolve: () => getItems(),
           }
        }
    })
});

如果您的列表不是那么简单,例如,itemList 实际上有两个字段(oldItems、newItems - 都是列表),您应该定义一个单独的类型。记得相应地修改 resolve 函数:

itemList: {
  type: itemListType,
  resolve: () => {
    // get new items
    // get old items
    return {
      newItems, 
      oldItems
    };
  },
},

(顺便说一下,您的代码有一些语法错误,例如 itemsList、itemList、itemsListType、itemListType。我已经编辑了您的问题。更改将在我的编辑被批准后显示。)