跳至主要内容

使用全局节点 ID

您可以通过 REST API 获取对象的全局节点 ID,并在 GraphQL 操作中使用它们。

您可以使用 REST API 或 GraphQL API 访问 GitHub 中的大多数对象(用户、议题、拉取请求等)。您可以在 REST API 中找到许多对象的 全局节点 ID,并在 GraphQL 操作中使用这些 ID。有关详细信息,请参阅 在 REST API 资源中预览 GraphQL API 节点 ID

注意

在 REST 中,全局节点 ID 字段名为 node_id。在 GraphQL 中,它是 node 接口上的 id 字段。想了解“node”在 GraphQL 中的含义,请参阅 GraphQL 入门指南

将全局节点 ID 用于实践

您可以遵循以下三个步骤来有效使用全局节点 ID

  1. 调用返回对象 node_id 的 REST 端点。
  2. 在 GraphQL 中查找对象的类型。
  3. 使用该 ID 和类型在 GraphQL 中进行直接节点查找。

让我们通过示例来演示。

1. 调用返回对象节点 ID 的 REST 端点

如果您 请求已认证的用户

curl -i --header "Authorization: Bearer YOUR-TOKEN" https://api.github.com/user

您将收到包含已认证用户的 node_id 的响应

{
  "login": "octocat",
  "id": 1,
  "avatar_url": "https://github.com/images/error/octocat_happy.gif",
  "gravatar_id": "",
  "url": "https://api.github.com/users/octocat",
  "html_url": "https://github.com/octocat",
  "followers_url": "https://api.github.com/users/octocat/followers",
  "following_url": "https://api.github.com/users/octocat/following{/other_user}",
  "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
  "organizations_url": "https://api.github.com/users/octocat/orgs",
  "repos_url": "https://api.github.com/users/octocat/repos",
  "events_url": "https://api.github.com/users/octocat/events{/privacy}",
  "received_events_url": "https://api.github.com/users/octocat/received_events",
  "type": "User",
  "site_admin": false,
  "name": "monalisa octocat",
  "company": "GitHub",
  "blog": "https://github.com/blog",
  "location": "San Francisco",
  "email": "octocat@github.com",
  "hireable": false,
  "bio": "There once was...",
  "public_repos": 2,
  "public_gists": 1,
  "followers": 20,
  "following": 0,
  "created_at": "2008-01-14T04:33:35Z",
  "updated_at": "2008-01-14T04:33:35Z",
  "private_gists": 81,
  "total_private_repos": 100,
  "owned_private_repos": 100,
  "disk_usage": 10000,
  "collaborators": 8,
  "two_factor_authentication": true,
  "plan": {
    "name": "Medium",
    "space": 400,
    "private_repos": 20,
    "collaborators": 0
  },
  "node_id": "MDQ6VXNlcjU4MzIzMQ=="
}

2. 在 GraphQL 中查找对象类型

在此示例中,node_id 的值为 MDQ6VXNlcjU4MzIzMQ==。您可以使用此值在 GraphQL 中查询同一对象。

不过,您需要先了解对象的 类型。您可以使用简单的 GraphQL 查询来检查类型。

query {
  node(id:"MDQ6VXNlcjU4MzIzMQ==") {
     __typename
  }
}

此类查询——即通过 ID 查找节点——称为“直接节点查找”。

运行此查询时,您会看到 __typenameUser

3. 在 GraphQL 中进行直接节点查找

确认类型后,您可以使用 inline fragment(内联片段) 通过其 ID 访问对象并返回额外数据。在本例中,我们定义了想要查询的 User 的字段

query {
  node(id:"MDQ6VXNlcjU4MzIzMQ==") {
   ... on User {
      name
      login
    }
  }
}

此类查询是通过全局节点 ID 查找对象的标准方法。

在迁移中使用全局节点 ID

在构建使用 REST API 或 GraphQL API 的集成时,最佳实践是持久化全局节点 ID,以便在不同 API 版本之间轻松引用对象。有关处理从 REST 向 GraphQL 迁移的更多信息,请参阅 从 REST 迁移到 GraphQL

© . This site is unofficial and not affiliated with GitHub, Inc.