-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
221 lines (200 loc) · 6.56 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
/* ================================================================================
notion-github-sync.
Glitch example: https://glitch.com/edit/#!/notion-github-sync
Find the official Notion API client @ https://github.com/makenotion/notion-sdk-js/
================================================================================ */
const { Client } = require("@notionhq/client")
const { Octokit } = require("octokit")
const _ = require("lodash")
const octokit = new Octokit({ auth: process.env.PERSONAL_GITHUB_ACCESS_KEY })
const notion = new Client({ auth: process.env.NOTION_KEY })
const databaseId = process.env.NOTION_DATABASE_ID
const OPERATION_BATCH_SIZE = 10
/**
* Local map to store GitHub issue ID to its Notion pageId.
* { [issueId: string]: string }
*/
const gitHubIssuesIdToNotionPageId = {}
/**
* Initialize local data store.
* Then sync with GitHub.
*/
setInitialGitHubToNotionIdMap().then(syncNotionDatabaseWithGitHub)
/**
* Get and set the initial data store with issues currently in the database.
*/
async function setInitialGitHubToNotionIdMap() {
const currentIssues = await getIssuesFromNotionDatabase()
for (const { pageId, issueNumber } of currentIssues) {
gitHubIssuesIdToNotionPageId[issueNumber] = pageId
}
}
async function syncNotionDatabaseWithGitHub() {
// Get all issues currently in the provided GitHub repository.
console.log("\nFetching issues from Notion DB...")
const issues = await getGitHubIssuesForRepository()
console.log(`Fetched ${issues.length} issues from GitHub repository.`)
// Group issues into those that need to be created or updated in the Notion database.
const { pagesToCreate, pagesToUpdate } = getNotionOperations(issues)
// Create pages for new issues.
console.log(`\n${pagesToCreate.length} new issues to add to Notion.`)
await createPages(pagesToCreate)
// Updates pages for existing issues.
console.log(`\n${pagesToUpdate.length} issues 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, issueNumber: number }>>}
*/
async function getIssuesFromNotionDatabase() {
const pages = []
let cursor = undefined
while (true) {
const { results, next_cursor } = await notion.databases.query({
database_id: databaseId,
start_cursor: cursor,
})
pages.push(...results)
if (!next_cursor) {
break
}
cursor = next_cursor
}
console.log(`${pages.length} issues successfully fetched.`)
return pages.map(page => {
return {
pageId: page.id,
issueNumber: page.properties["Issue Number"].number,
}
})
}
/**
* Gets issues from a GitHub repository. Pull requests are omitted.
*
* https://docs.github.com/en/rest/guides/traversing-with-pagination
* https://docs.github.com/en/rest/reference/issues
*
* @returns {Promise<Array<{ number: number, title: string, state: "open" | "closed", comment_count: number, url: string }>>}
*/
async function getGitHubIssuesForRepository() {
const issues = []
const iterator = octokit.paginate.iterator(octokit.rest.issues.listForRepo, {
owner: process.env.REPO_OWNER,
repo: process.env.REPO_NAME,
state: "all",
per_page: 100,
})
for await (const { data } of iterator) {
for (const issue of data) {
if (!issue.pull_request) {
issues.push({
number: issue.number,
title: issue.title,
state: issue.state,
comment_count: issue.comments,
url: issue.html_url,
})
}
}
}
return issues
}
/**
* Determines which issues already exist in the Notion database.
*
* @param {Array<{ number: number, title: string, state: "open" | "closed", comment_count: number, url: string }>} issues
* @returns {{
* pagesToCreate: Array<{ number: number, title: string, state: "open" | "closed", comment_count: number, url: string }>;
* pagesToUpdate: Array<{ pageId: string, number: number, title: string, state: "open" | "closed", comment_count: number, url: string }>
* }}
*/
function getNotionOperations(issues) {
const pagesToCreate = []
const pagesToUpdate = []
for (const issue of issues) {
const pageId = gitHubIssuesIdToNotionPageId[issue.number]
if (pageId) {
pagesToUpdate.push({
...issue,
pageId,
})
} else {
pagesToCreate.push(issue)
}
}
return { pagesToCreate, pagesToUpdate }
}
/**
* Creates new pages in Notion.
*
* https://developers.notion.com/reference/post-page
*
* @param {Array<{ number: number, title: string, state: "open" | "closed", comment_count: number, url: string }>} pagesToCreate
*/
async function createPages(pagesToCreate) {
const pagesToCreateChunks = _.chunk(pagesToCreate, OPERATION_BATCH_SIZE)
for (const pagesToCreateBatch of pagesToCreateChunks) {
await Promise.all(
pagesToCreateBatch.map(issue =>
notion.pages.create({
parent: { database_id: databaseId },
properties: getPropertiesFromIssue(issue),
})
)
)
console.log(`Completed batch size: ${pagesToCreateBatch.length}`)
}
}
/**
* Updates provided pages in Notion.
*
* https://developers.notion.com/reference/patch-page
*
* @param {Array<{ pageId: string, number: number, title: string, state: "open" | "closed", comment_count: number, url: string }>} pagesToUpdate
*/
async function updatePages(pagesToUpdate) {
const pagesToUpdateChunks = _.chunk(pagesToUpdate, OPERATION_BATCH_SIZE)
for (const pagesToUpdateBatch of pagesToUpdateChunks) {
await Promise.all(
pagesToUpdateBatch.map(({ pageId, ...issue }) =>
notion.pages.update({
page_id: pageId,
properties: getPropertiesFromIssue(issue),
})
)
)
console.log(`Completed batch size: ${pagesToUpdateBatch.length}`)
}
}
//*========================================================================
// Helpers
//*========================================================================
/**
* Returns the GitHub issue to conform to this database's schema properties.
*
* @param {{ number: number, title: string, state: "open" | "closed", comment_count: number, url: string }} issue
*/
function getPropertiesFromIssue(issue) {
const { title, number, state, comment_count, url } = issue
return {
Name: {
title: [{ type: "text", text: { content: title } }],
},
"Issue Number": {
number,
},
State: {
select: { name: state },
},
"Number of Comments": {
number: comment_count,
},
"Issue URL": {
url,
},
}
}