Notify of new Github repo stars

bun · 67 lines
1
import { setState, getState } from "@orvanta/client@1";
2
import { Octokit } from "@octokit/rest@19.0.5";
3
 
4
const MAX_ITEMS = 500;
5
 
6
/**
7
 * @returns A list of starrers in descending order of when they starred.
8
 * The maximum number of returned items is 500.
9
 */
10
type Github = {
11
  token: string;
12
};
13
export async function main(auth: Github, owner: string, repo: string) {
14
  const octokit = new Octokit({
15
    auth: auth.token,
16
  });
17
  const lastUpdate = (await getState()) || 0;
18
 
19
  const starCount = (await octokit.repos.get({ owner, repo })).data
20
    .stargazers_count;
21
  let lastPage =
22
    +(starCount / 100).toFixed(0) + (starCount % 100 === 0 ? 0 : 1);
23
  const newStarrers: Starrer[] = [];
24
 
25
  await setState(Date.now());
26
  let runLoop = true;
27
  do {
28
    const response = await octokit.activity.listStargazersForRepo({
29
      owner,
30
      repo,
31
      per_page: 100,
32
      page: lastPage--,
33
      headers: {
34
        accept: "application/vnd.github.star+json",
35
      },
36
    });
37
    for (let i = response.data.length - 1; i >= 0; i--) {
38
      const entry = response.data[i];
39
      if (!entry || !entry.user) continue;
40
      const starredAt = new Date(entry.starred_at).getTime();
41
      if (starredAt < lastUpdate) {
42
        runLoop = false;
43
        break;
44
      }
45
      const { id, login, type, url, email, name } = entry.user;
46
      newStarrers.push({ id, starredAt, login, type, url, email, name });
47
      if (newStarrers.length >= MAX_ITEMS) {
48
        await setState(newStarrers.at(-1)?.starredAt);
49
        runLoop = false;
50
        break;
51
      }
52
    }
53
  } while (runLoop);
54
  console.log(newStarrers.length);
55
  return newStarrers;
56
}
57
 
58
interface Starrer {
59
  id: number;
60
  login: string;
61
  type: string;
62
  url: string;
63
  starredAt: number;
64
  email?: string | null;
65
  name?: string | null;
66
}
67
 
Orvanta Hub — community scripts, flows, apps & resource types.