-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
328 lines (296 loc) · 10 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/* ================================================================================
stars-to-notion
Save stars in a Notion database automatically with GitHub Actions
GitHub: https://github.com/algers/stars-to-notion
================================================================================ */
const { Client, LogLevel } = require("@notionhq/client")
const dotenv = require("dotenv")
const { Octokit } = require("octokit")
const _ = require("lodash")
dotenv.config()
if (!(
process.env.GH_STARS_USER &&
process.env.GH_USER_TOKEN &&
process.env.NOTION_KEY &&
process.env.NOTION_DATABASE_ID
)) {
console.error("Missing environment variable.")
process.exit(1)
}
const octokit = new Octokit({
auth: process.env.GH_USER_TOKEN,
request: {},
})
const notion = new Client({
auth: process.env.NOTION_KEY,
logLevel: LogLevel.DEBUG,
})
const databaseId = process.env.NOTION_DATABASE_ID
const OPERATION_BATCH_SIZE = 1
/**
* Local map to store GitHub star ID to its Notion pageId.
* { [starId: string]: string }
*/
const gitHubStarsIdToNotionPageId = {}
/**
* Initialize local data store.
* Then sync with GitHub.
*/
setInitialGitHubToNotionIdMap().then(syncNotionDatabaseWithGitHub)
/**
* Get and set the initial data store with stars currently in the database.
*/
async function setInitialGitHubToNotionIdMap() {
const currentStars = await getStarsFromNotionDatabase()
for (const { pageId, starId }
of currentStars) {
gitHubStarsIdToNotionPageId[starId] = pageId
}
}
async function syncNotionDatabaseWithGitHub() {
// Get all user's currently starred repositories
console.log("\nFetching stars from Notion DB...")
const stars = await getGitHubStarsForUser()
console.log(`Fetched ${stars.length} stars from GitHub user.`)
// Group stars into those that need to be created or updated in the Notion database.
const { pagesToCreate, pagesToUpdate } = getNotionOperations(stars)
// Create pages for new stars.
console.log(`\n${pagesToCreate.length} new stars to add to Notion.`)
await createPages(pagesToCreate)
// Updates pages for existing stars.
console.log(`\n${pagesToUpdate.length} stars to update in Notion.`)
await updatePages(pagesToUpdate)
// Success!
console.log("\n✅ Notion database is synced with GitHub.")
}
/**
* Gets pages from the Notion database.
*
* @returns {Promise<Array<{ pageId: string, starId: number }>>}
*/
async function getStarsFromNotionDatabase() {
const pages = []
let cursor = undefined
while (true) {
const { results, next_cursor } = await notion.databases.query({
page_size: 10,
database_id: databaseId,
start_cursor: cursor,
})
pages.push(...results)
if (!next_cursor) {
break
}
cursor = next_cursor
}
console.log(`${pages.length} stars successfully fetched from Notion.`)
return pages.map(page => {
return {
pageId: page.id,
starId: page.properties["Star ID"].number,
}
})
}
/**
* Gets stars from a GitHub user.
*
* https://docs.github.com/en/rest/guides/traversing-with-pagination
* https://docs.github.com/en/rest/reference/activity#list-stargazers
*
* @returns {Promise<Array<{ id: number, title: string, labels: array, url: string, starred: number, stargazers: number, forks: number, language: string, description: string, watchers: number, created: string, homepage: string, size: number, pushed: string }>>}
*/
async function getGitHubStarsForUser() {
const stars = []
const iterator = octokit.paginate.iterator(
octokit.rest.activity.listReposStarredByUser, {
headers: {
accept: "application/vnd.github.v3.star+json",
},
username: process.env.GH_STARS_USER,
per_page: 100,
}
)
for await (const { data }
of iterator) {
for (const star of data) {
stars.push({
id: star.repo.id,
title: star.repo.full_name,
url: star.repo.html_url,
starred: star.starred_at,
labels: star.repo.topics,
stargazers: star.repo.stargazers_count,
forks: star.repo.forks_count,
language: star.repo.language,
description: star.repo.description,
pushed: star.repo.pushed_at,
watchers: star.repo.watchers_count,
created: star.repo.created_at,
homepage: star.repo.homepage,
size: star.repo.size,
})
}
}
return stars
}
/**
* Determines which stars already exist in the Notion database.
*
* @param {Array<{ id: number, title: string, labels: array, url: string, starred: number, stargazers: number, forks: number, language: string, description: string, watchers: number, created: string, homepage: string, size: number, pushed: string }>}
* @returns {{
* pagesToCreate: Array<{ id: number, title: string, labels: array, url: string, starred: number, stargazers: number, forks: number, language: string, description: string, watchers: number, created: string, homepage: string, size: number, pushed: string }>;
* pagesToUpdate: Array<{ pageId: string, id: number, title: string, labels: array, url: string, starred: number, stargazers: number, forks: number, language: string, description: string, watchers: number, created: string, homepage: string, size: number, pushed: string }>
* }}
*/
function getNotionOperations(stars) {
const pagesToCreate = []
const pagesToUpdate = []
for (const star of stars) {
const pageId = gitHubStarsIdToNotionPageId[star.id]
if (pageId) {
pagesToUpdate.push({
...star,
pageId,
})
} else {
pagesToCreate.push(star)
}
}
return {
pagesToCreate,
pagesToUpdate,
}
}
/**
* Creates new pages in Notion.
*
* https://developers.notion.com/reference/post-page
*
* @param {Array<{ id: number, title: string, labels: array, url: string, starred: number, stargazers: number, forks: number, language: string, description: string, watchers: number, created: string, homepage: string, size: number, pushed: string }>} pagesToCreate
*/
async function createPages(pagesToCreate) {
const pagesToCreateChunks = _.chunk(pagesToCreate, OPERATION_BATCH_SIZE)
for (const pagesToCreateBatch of pagesToCreateChunks) {
console.log(pagesToCreateBatch)
await Promise.all(
pagesToCreateBatch.map(star =>
notion.pages.create({
parent: {
database_id: databaseId,
},
properties: getPropertiesFromStar(star),
})
)
)
console.log(`Completed batch size: ${pagesToCreateBatch.length}`)
}
}
/**
* Updates provided pages in Notion.
*
* https://developers.notion.com/reference/patch-page
*
* @param {Array<{ pageId: string, id: number, title: string, labels: array, url: string, starred: number, stargazers: number, forks: number, language: string, description: string, watchers: number, created: string, homepage: string, size: number, pushed: string }>} pagesToUpdate
*/
async function updatePages(pagesToUpdate) {
const pagesToUpdateChunks = _.chunk(pagesToUpdate, OPERATION_BATCH_SIZE)
for (const pagesToUpdateBatch of pagesToUpdateChunks) {
await Promise.all(
pagesToUpdateBatch.map(({ pageId, ...star }) =>
notion.pages.update({
page_id: pageId,
properties: getPropertiesFromStar(star),
})
)
)
console.log(`Completed batch size: ${pagesToUpdateBatch.length}`)
}
}
//*========================================================================
// Helpers
//*========================================================================
/**
* Returns the GitHub star to conform to this database's schema properties.
*
* @param {{ id: number, title: string, labels: array, url: string, starred: number, stargazers: number, forks: number, language: string, description: string, watchers: number, created: string, homepage: string, size: number, pushed: string, }} star
*/
function getPropertiesFromStar(star) {
const {
id,
title,
labels,
url,
starred,
stargazers,
forks,
language,
description,
watchers,
created,
homepage,
size,
pushed,
} = star
const item = {
"Name": {
title: [{ type: "text", text: { content: title } }],
},
"Star ID": {
number: id,
},
"URL": {
url,
},
"Starred": {
date: {
start: starred,
},
},
"Created": {
date: {
start: created,
},
},
"Stargazers": {
number: stargazers,
},
"Watchers": {
number: watchers,
},
"Size (Kb)": {
number: size,
},
"Forks": {
number: forks,
},
"Pushed": {
date: {
start: pushed,
},
},
"Homepage": ((homepage && homepage !== '') ? {
url: homepage,
} : null),
"Description": (description ? {
rich_text: [{
type: "text",
text: {
content: description,
},
}, ],
} : null),
"Language": (language ? {
select: {
name: language,
},
} : null),
"Topics": (labels ? {
multi_select: labels.map(topic => {
return {
name: topic,
}
}),
} : null),
}
return Object.fromEntries(Object.entries(item).filter(([_, v]) => v != null))
}