javascript - 如何正确使用 GraphQLList 和 GraphQLInterfaceType?

标签 javascript graphql

我开始使用 GraphQL。我正在尝试将数据解析为 GraphQL 类型。我不明白为什么以下内容不起作用。

鉴于此数据:

{
    "kind": "youtube#searchListResponse",
    "etag": "\"CuSCwMPVmgi8taDtE2LV6HdgkN0/USvbH1nSht52L3y8EP6BIwVRhgM\"",
    "items": [{
        "kind": "youtube#searchResult",
        "etag": "\"CuSCwMPVmgi8taDtE2LV6HdgkN0/xpywjUARlQ0Ai4IucTvXRNCfTcE\"",
        "id": {
            "kind": "youtube#video",
            "videoId": "zvRbU1Ql5BQ"
        }
    }]
}

这是输入的代码。

const ItemType = new GraphQLInterfaceType({
  name: 'Item',
  fields: {
    kind: { type: StringType },
  },
});

const YoutubeDataType = new GraphQLObjectType({
  name: 'PublicYoutube',
  fields: {
    kind: { type: new GraphQLNonNull(StringType) },
    etag: { type: new GraphQLNonNull(StringType) },
      items: { type: new GraphQLList(ItemType) },  // returns null
    // items: { type: StringType }, // returns "[object Object]"... so it's being passed in
  },
});

这是通过 GraphiQL 返回的内容。为什么 items 等于 null

{
  "data": {
    "publicyoutube": {
      "kind": "youtube#searchListResponse",
      "etag": "\"CuSCwMPVmgi8taDtE2LV6HdgkN0/OspGzY61uG9sSD_AWlfwkTBjG-8\"",
      "items": [
        null
      ]
    }
  },
  "errors": [
    {
      "message": "Cannot read property 'length' of undefined"
    }
  ]
}

感谢您的帮助。

最佳答案

我误解了 GraphQLInterfaceType 的用途并且使用了错误的方法。而不是使用GraphQLInterfaceType,它应该是GraphQLObjectType;

const ItemType = new GraphQLObjectType({
  name: 'Item',
  fields: {
    kind: { type: StringType },
  },
});

const YoutubeDataType = new GraphQLObjectType({
  name: 'PublicYoutube',
  fields: {
    kind: { type: new GraphQLNonNull(StringType) },
    etag: { type: new GraphQLNonNull(StringType) },
      items: { type: new GraphQLList(ItemType) },  // returns null
    // items: { type: StringType }, // returns "[object Object]"... so it's being passed in
  },
});

输出:

{
  "data": {
    "publicyoutube": {
      "kind": "youtube#searchListResponse",
      "etag": "\"CuSCwMPVmgi8taDtE2LV6HdgkN0/-aZNXBVLYOJwPMdleXmbTlJSo_E\"",
      "items": [
        {
          "kind": "youtube#searchResult"
        }
      ]
    }
  }
}

关于javascript - 如何正确使用 GraphQLList 和 GraphQLInterfaceType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814486/

相关文章:

react-native - 如何将参数传递给graphql片段?

python - 不知道如何转换 Django 字段技能(<class 'taggit.managers.TaggableManager' >)?图表数据库

javascript - 继电器:无法读取 null 的属性 'fetchKey'

flutter - 如何使用 Riverpod 处理身份验证 token 和 GraphQL 客户端?

java - JSP 文件在 Eclipse 中工作正常但在 Tomcat/webapps 中不工作

javascript - Mobx 在 Action 之外改变可观察值

javascript - 如何动态地将 2 个 Canvas 添加到文档中以使它们重叠?

GraphQL:如何通过 Playground 传递查询变量?

javascript - 如何使用无内存函数将 256 个唯一字符串映射到整数 (0..255)

javascript - 无法添加数组索引