使用Github API获取排名

更新于 

看到有人使用Github 提供的API做了GitHub rank的网站,由于以前没有使用过Github的API,所以打算自己动手尝试一下。在线效果

1. Token 生成

使用API前需要先申请开发者Token,在Settings --> Developer settings --> Personal access tokens里自行生成。生成好的token要记好,不然后面就看不见了,只能重新生成。

https://file.vwood.xyz/2024/06/24/upload_z5gn7z6dzmo3cxwxczupjfao4rxfming.png

2. API对接

安装octokit

npm install octokit

使用

import { Octokit } from "octokit"; const octokit = new Octokit({ auth: 'YOUR-TOKEN' });

查询排名前100的数据列表

查询followers大于1000的用户,取前100条数据

const getUsers = async () => { const q = "followers:>1000 location:China"; const result = await octokit.request("GET /search/users", { q, per_page: 100, // 每页最多100条数据 }); return result.data.items; };

数据结构如下:

[ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "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 } ]

更新信息查看官网文档

根据login获取用户信息

上面是批量获取的用户信息缺少我们想要的数据,通过用户的login获取详细信息,比如:namebloglocationcompanyfollowers等数据,更多字段查看官网文档;

const getUsersInfo = async (items = []) => { const userInfoMap = {} for (let user of items) { if (!userInfoMap[user.login]) { const result = await octokit.request(`GET /users/${user.login}`); const userInfo = result.data; if (userInfo) { userInfoMap[user.id] = { html_url: userInfo.html_url, login: userInfo.login, name: userInfo.name, blog: userInfo.blog, location: userInfo.location, company: userInfo.company, followers: userInfo.followers, following: userInfo.following, public_repos: userInfo.public_repos, twitter_username: userInfo.twitter_username, created_at: userInfo.created_at, }; } } } return userInfoMap; };

数据更新

上面的代码基本就能实现从github获取排名数据了,如果每次都通过接口获取,那耗时会相当的长,所以可以将数据缓存起来,每天更新一次数据即可。

通过服务器的crontabs定时功能,每天凌晨拉取一次,我将上面的代码放到了github-rank.mjs里,将获取到的数据存在json文件里,下面时添加到crontabs的配置。

0 0 * * * node /app/cron/github-rank.mjs >> /var/log/cron.log

前端使用nextjs在服务器渲染时读取json文件的数据即可。

如果使用的docker,需要注意alpine版本crontab的目录是var/spool/cron/crontabs,不是/etc/cron.d