惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
F
Fortinet All Blogs
D
Docker
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
罗磊的独立博客
Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
J
Java Code Geeks
T
The Blog of Author Tim Ferriss
U
Unit 42
N
Netflix TechBlog - Medium
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
云风的 BLOG
云风的 BLOG
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Proofpoint News Feed
G
Google Developers Blog
H
Help Net Security

szhshp 的第三边境研究所

假设, AI 把我代替的那一刻真的到来 | szhshp 的第三边境研究所 小傻瓜都能懂的 AstrBot QQ 机器人集成 MCP 功能实战指南 | szhshp 的第三边境研究所 《智人之上: 从石器时代到 AI 时代的信息网络简史》阅读笔记 | szhshp 的第三边境研究所 iPadOS 26 无法设置空间场景图片壁纸的解决方法 | szhshp 的第三边境研究所 《一路云海》(终) | szhshp 的第三边境研究所 《一路云海》(四): 如何不按套路旅行 | szhshp 的第三边境研究所 《一路云海》(三): In Ya Mellow Tone | szhshp 的第三边境研究所 《一路云海》(二): 关西世博参观纪实 | szhshp 的第三边境研究所 《一路云海》(一): 新的征程 | szhshp 的第三边境研究所 2025 大阪世博会 [ 3 天前-先到先得 ] 阶段 场馆预约必中独家攻略 | szhshp 的第三边境研究所 Hackathon 随想 | szhshp 的第三边境研究所 一杯双皮奶 | szhshp 的第三边境研究所 Armbian + CasaOS + NAS 配置指南 | szhshp 的第三边境研究所 Docker 构建镜像报错: error getting credentials - err: exit status 1, out: `` | szhshp 的第三边境研究所 Disqus RIP! 论过高的维护成本如何治疗固执的坏习惯 | szhshp 的第三边境研究所 炸弹猫桌游变体规则 | szhshp 的第三边境研究所 《小岛经济学》阅读笔记 | szhshp 的第三边境研究所 《金钱心理学》阅读笔记 | szhshp 的第三边境研究所 为知笔记 RIP: 迁移剩余的笔记 | szhshp 的第三边境研究所 2025 博客第十年展望 - 再见我的过去 | szhshp 的第三边境研究所 我在独立游戏里面致敬的作品 | szhshp 的第三边境研究所 《How to make thing faster》阅读笔记 | szhshp 的第三边境研究所 《The Art of Clean Code》阅读笔记 | szhshp 的第三边境研究所 《Clean Architecture: A Craftsman Guide to Software Structure and Design》阅读笔记 | szhshp 的第三边境研究所 《How AI Works》阅读笔记 | szhshp 的第三边境研究所 游戏策划废案 - Project Uranus | szhshp 的第三边境研究所 游戏策划废案 - Project X | szhshp 的第三边境研究所 人生第一款独立游戏开发复盘 | szhshp 的第三边境研究所 Trap of Life | szhshp 的第三边境研究所 如果我用手搓了个暗物质雏形 | szhshp 的第三边境研究所
Github GraphQL API - Data Integration | szhshp 的第三边境...
2021-01-28 · via szhshp 的第三边境研究所

Meta

目录

Requirements

If you have below requirements:

  • I want to show github Deployment Status in my site
  • I want to show Issue Details in my blog
  • I want to display detailed Commit History of a project in official website

Now let’s rock with Github API

Implementation

REST API

// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo
const octokit = new Octokit({ auth: `personal-access-token123` });

const response = await octokit.request("GET /orgs/{org}/repos", {
  org: "octokit",
  type: "private",
});

See @octokit/request for full documentation of the .request method.

Restful API is fine that you may get everything you want.

But I recommand to use GraphQL API

GraphQL API

Why GraphQL?

  • Strongly Typed
  • Extensible
  • Pick the column you desired
  • Popular
  • Solve the over-fetching and under-fetching problem

Example

const octokit = new Octokit({ auth: `personal-access-token123` });

const response = await octokit.graphql(
  `query ($login: String!) {
    organization(login: $login) {
      repositories(privacy: PRIVATE) {
        totalCount
      }
    }
  }`,
  { login: "octokit" }
);

See @octokit/graphql for full documentation of the .graphql method.

Compose a Github GraphQL Query

The Github GraphQL API documentation is obscure. 😒

  1. Get your PAT first
  2. Determine if you want a Query or a Mutation
  3. Find your query/mutation
  4. Check the return type
  5. Write it to your code

Step by Step Guide

Get your PAT

https://github.com/settings/tokens/new?scopes=repo

Make sure you checked the desired data.

Otherwise the specific field will got null in client side.

Determine if you want a Query or a Mutation

https://docs.github.com/en/graphql/reference

  • For query data you may need a Query
  • For add/update/delete data you may need a Mutation

Find your query

https://docs.github.com/en/graphql/reference/queries#repository

I use repository query and it accepts 2 args:

{
  repository(owner: "${owner}", name: "${repo}") {
    ...
  }
}

Check the return type

https://docs.github.com/en/graphql/reference/objects#repository

We have deployments available in repository object.

And deployments is a DeploymentConnection.

And check deployments, you can add the field you need to your query.

{
  repository(owner: "${owner}", name: "${repo}") {
    deployments(last: 1) {
      nodes {
        id
        createdAt
        updatedAt
        environment
        state
      }
    }
    name
    ref(qualifiedName: "refs/heads/master") {
      target {
        ... on Commit {
          YTDCommits: history(since: "${moment().clone().startOf("year").toISOString()}") {
            totalCount
          }
          monthlyCommits: history(since: "${moment().clone().startOf("month").toISOString()}") {
            totalCount
          }
        }
      }
    }
  }
}

I added 2 custom field YTDCommits & monthlyCommits to generate the MTD and YTD history count.

Debug your query

https://docs.github.com/en/graphql/overview/explorer

Full code

async (): Promise<void> => {
  try {
    const octokit = new Octokit({ auth: accessToken });

    const { repository } = await octokit.graphql(
      `
        {
          repository(owner: "${owner}", name: "${repo}") {
            deployments(last: 1) {
              nodes {
                id
                createdAt
                updatedAt
                environment
                state
              }
            }
            name
            ref(qualifiedName: "refs/heads/master") {
              target {
                ... on Commit {
                  YTDCommits: history(since: "${moment().clone().startOf("year").toISOString()}") {
                    totalCount
                  }
                  monthlyCommits: history(since: "${moment().clone().startOf("month").toISOString()}") {
                    totalCount
                  }
                }
              }
            }
          }
        }
      `,
      {
        headers: {
          authorization: `token ${accessToken}`,
        },
      },
    );



    setStatus(repository?.deployments?.nodes[0]?.state || "PENDING");
    setCreateAt(repository?.deployments?.nodes[0]?.createdAt);
    setMonthlyCommits(repository?.ref?.target?.monthlyCommits?.totalCount);
    setYTDCommits(repository?.ref?.target?.YTDCommits?.totalCount);

  } catch (errorMessage) {
    logger({ type: "error", message: errorMessage });
  }
}