本文首发于个人博客 Cyy’s Blog
转载请注明出处 https://cyyjs.top/blog/5d5e82b4d7933a1f338b105e

本文讲解GitHub GraphQL API v4 的简单使用方法

# 认证

要与GitHubCraphQL服务器通信,需要现有可用的OAuth令牌。点此打开创建token页面,完成申请。官方申请教程

# GraphQL端点

GraphQL API只有一个地址为:https://api.github.com/graphql

# 发起请求

# 设置header

headers: {
  Authorization: 'bearer token'
}

# 简单curl请求示例

curl -H "Authorization: bearer token" -X POST -d " \
 { \
   \"query\": \"query { viewer { login }}\" \
 } \
" https://api.github.com/graphql

# 在Node.js中发起请求

# 安装请求客户端

yarn add graphql-request

# 使用示例

const { GraphQLClient } = require('graphql-request')
const endpoint = 'https://api.github.com/graphql'

const graphQLClient = new GraphQLClient(endpoint, {
  headers: {
    authorization: `bearer ${token}`
  }
})

// 查询指定组织下代码库列表
const query = `
  { 
    organization (login:"cyytemplate"){
      repositories(first:100){
        totalCount
        nodes {
          name
          description
          resourcePath
          updatedAt
        }
      }
    }
  }
`
const data = await graphQLClient.request(query)

// 查询指定组织下指定仓库名的代码数据
const query = `
  { 
    organization (login:"cyytemplate"){
      repository(name:"${name}"){
        name
        description
        resourcePath
        updatedAt
      }
    }
  }
`
const data = await graphQLClient.request(query)

# explorer

官方提供的在线请求工具

# 注意事项

不要把GitHub生成的token编码到代码中,并提交到GitHub,GitHub的安全机制,会检查到,并立刻将该token删除

# 参考连接

GitHub API
graphql