-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathfetchGitHub.ts
More file actions
372 lines (332 loc) · 10.9 KB
/
fetchGitHub.ts
File metadata and controls
372 lines (332 loc) · 10.9 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { getPayload } from 'payload'
import config from '@payload-config'
import sanitizeSlug from '../utilities/sanitizeSlug'
const { GITHUB_ACCESS_TOKEN } = process.env
const headers = {
Authorization: `Bearer ${GITHUB_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
}
type ExistingDiscussion = {
docId: string
githubID: string
}
async function fetchGitHub(): Promise<void> {
if (!GITHUB_ACCESS_TOKEN) {
console.log('[fetchGitHub] No GitHub access token found - skipping discussions retrieval')
return
}
console.time('[fetchGitHub] Total duration')
console.log('[fetchGitHub] Starting GitHub discussions sync...')
const discussionData: any = []
const createQuery = (cursor = null, hasNextPage: boolean): string => {
const queryLine =
cursor && hasNextPage
? `(first: 100, categoryId: "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMzY4NTUw", after: "${
cursor as string
}")`
: `(first: 100, categoryId: "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMzY4NTUw")`
return `query {
repository(owner:"payloadcms", name:"payload") {
discussions${queryLine} {
pageInfo {
hasNextPage
endCursor
}
nodes {
title
bodyHTML
url
number
createdAt
upvoteCount,
category {
isAnswerable
id
}
author {
login
avatarUrl
url
}
comments(first: 30) {
totalCount,
edges {
node {
author {
login
avatarUrl
url
}
bodyHTML
createdAt
replies(first: 30) {
edges {
node {
author {
login
avatarUrl
url
}
bodyHTML
createdAt
}
}
}
}
}
}
answer {
author {
login
avatarUrl
url
}
bodyHTML
createdAt
replies(first: 30) {
edges {
node {
author {
login
avatarUrl
url
}
bodyHTML
createdAt
}
}
}
}
answerChosenAt
answerChosenBy {
login
}
}
}
}
}`
}
const initialReq: any = await fetch('https://api.github.com/graphql', {
body: JSON.stringify({
query: createQuery(null, false),
}),
headers,
method: 'POST',
}).then((res) => res.json())
if (initialReq.errors) {
console.error('[fetchGitHub] GitHub API returned errors:', JSON.stringify(initialReq.errors))
throw new Error(`GitHub API error: ${initialReq.errors[0]?.message || 'Unknown error'}`)
}
if (!initialReq.data?.repository?.discussions) {
console.error('[fetchGitHub] Unexpected GitHub API response:', JSON.stringify(initialReq))
throw new Error('GitHub API returned unexpected response structure')
}
discussionData.push(...initialReq.data.repository.discussions.nodes)
let hasNextPage = initialReq.data.repository.discussions.pageInfo.hasNextPage
let cursor = initialReq.data.repository.discussions.pageInfo.endCursor
while (hasNextPage) {
let nextReq
const retries = 3
let success = false
// Retry logic for timeouts
for (let attempt = 0; attempt <= retries && !success; attempt++) {
try {
nextReq = await fetch('https://api.github.com/graphql', {
body: JSON.stringify({
query: createQuery(cursor, hasNextPage),
}),
headers,
method: 'POST',
}).then((res) => res.json())
// Check for timeout or service errors in the response
if (nextReq.message && nextReq.message.includes("couldn't respond")) {
if (attempt < retries) {
console.warn(
`[fetchGitHub] GitHub API timeout, retrying in 3s (attempt ${attempt + 1}/${retries + 1})`,
)
await new Promise((resolve) => setTimeout(resolve, 3000))
continue
} else {
console.error('[fetchGitHub] GitHub API timeout after retries:', nextReq.message)
throw new Error(`GitHub API timeout: ${nextReq.message}`)
}
}
if (nextReq.errors) {
console.error('[fetchGitHub] GitHub API returned errors:', JSON.stringify(nextReq.errors))
throw new Error(`GitHub API error: ${nextReq.errors[0]?.message || 'Unknown error'}`)
}
if (!nextReq.data?.repository?.discussions) {
console.error('[fetchGitHub] Unexpected GitHub API response:', JSON.stringify(nextReq))
throw new Error('GitHub API returned unexpected response structure')
}
success = true
} catch (error) {
if (attempt < retries) {
console.warn(
`[fetchGitHub] Error fetching discussions page, retrying (attempt ${attempt + 1}/${retries + 1}):`,
error.message,
)
await new Promise((resolve) => setTimeout(resolve, 3000))
} else {
throw error
}
}
}
if (!success || !nextReq) {
throw new Error('Failed to fetch GitHub discussions after retries')
}
discussionData.push(...nextReq.data.repository.discussions.nodes)
hasNextPage = nextReq.data.repository.discussions.pageInfo.hasNextPage
cursor = nextReq.data.repository.discussions.pageInfo.endCursor
}
console.log(`[fetchGitHub] Retrieved ${discussionData.length} discussions from GitHub`)
const formattedDiscussions = discussionData.map((discussion) => {
const { answer, answerChosenAt, answerChosenBy, category } = discussion
if (answer !== null && category.isAnswerable) {
const answerReplies = answer?.replies.edges.map((replyEdge) => {
const reply = replyEdge.node
return {
author: {
name: reply.author.login,
avatar: reply.author.avatarUrl,
url: reply.author.url,
},
body: reply.bodyHTML,
createdAt: reply.createdAt,
}
})
const formattedAnswer = {
author: {
name: answer.author?.login,
avatar: answer.author?.avatarUrl,
url: answer.author?.url,
},
body: answer.bodyHTML,
chosenAt: answerChosenAt,
chosenBy: answerChosenBy?.login,
createdAt: answer.createdAt,
replies: answerReplies?.length > 0 ? answerReplies : null,
}
const comments = discussion.comments.edges.map((edge) => {
const comment = edge.node
const replies = comment.replies.edges.map((replyEdge) => {
const reply = replyEdge.node
return {
author: {
name: reply.author.login,
avatar: reply.author.avatarUrl,
url: reply.author.url,
},
body: reply.bodyHTML,
createdAt: reply.createdAt,
}
})
return {
author: {
name: comment.author.login,
avatar: comment.author.avatarUrl,
url: comment.author.url,
},
body: comment.bodyHTML,
createdAt: comment.createdAt,
replies: replies?.length ? replies : null,
}
})
return {
id: String(discussion.number),
slug: sanitizeSlug(discussion.title),
answer: formattedAnswer,
author: {
name: discussion.author?.login,
avatar: discussion.author?.avatarUrl,
url: discussion.author?.url,
},
body: discussion.bodyHTML,
comments,
commentTotal: discussion.comments.totalCount,
createdAt: discussion.createdAt,
title: discussion.title,
upvotes: discussion.upvoteCount,
url: discussion.url,
}
}
return null
})
const filteredDiscussions = formattedDiscussions.filter((discussion) => discussion !== null)
console.log('[fetchGitHub] Fetching existing GitHub discussions from CMS...')
const payload = await getPayload({ config })
const existingDiscussionsResult = await payload.find({
collection: 'community-help',
where: {
communityHelpType: {
equals: 'github',
},
},
limit: 0,
depth: 0,
overrideAccess: true,
})
const existingDiscussions: ExistingDiscussion[] = existingDiscussionsResult.docs.map((thread) => ({
docId: thread.id,
githubID: thread.githubID as string,
}))
// Apply batch limit if set
const batchLimit = process.env.SYNC_BATCH_LIMIT
? parseInt(process.env.SYNC_BATCH_LIMIT, 10)
: filteredDiscussions.length
const discussionsToSync = filteredDiscussions.slice(0, batchLimit)
console.log(
`[fetchGitHub] Found ${existingDiscussions.length} existing discussions in CMS, ${filteredDiscussions.length} to process${
batchLimit < filteredDiscussions.length
? ` (processing ${batchLimit} this run due to SYNC_BATCH_LIMIT)`
: ''
}`,
)
const populateAll = discussionsToSync.map(async (discussion) => {
if (!discussion) {
return
}
const existingDiscussion = existingDiscussions.find((d) => d.githubID === discussion.id)
const data = {
slug: discussion.slug,
communityHelpJSON: discussion,
communityHelpType: 'github' as const,
githubID: discussion.id,
threadCreatedAt: discussion.createdAt,
title: discussion.title,
}
try {
if (existingDiscussion) {
// Update existing discussion
await payload.update({
id: existingDiscussion.docId,
collection: 'community-help',
data,
overrideAccess: true,
})
console.log(
`[fetchGitHub] Successfully updated discussion "${discussion.title}" (#${discussion.id})`,
)
} else {
// Create new discussion
await payload.create({
collection: 'community-help',
data,
overrideAccess: true,
})
console.log(
`[fetchGitHub] Successfully created discussion "${discussion.title}" (#${discussion.id})`,
)
}
} catch (error) {
console.error(
`[fetchGitHub] Exception processing discussion "${discussion.title}" (#${discussion.id}):`,
error,
)
}
})
await Promise.all(populateAll)
console.log('[fetchGitHub] Sync completed!')
console.timeEnd('[fetchGitHub] Total duration')
}
export default fetchGitHub