Skip to content

Commit 1e8fd36

Browse files
Leizhenpengsxzz
andauthored
feat: add retry logic to like ranking command (#81)
Co-authored-by: 三咲智子 Kevin Deng <[email protected]>
1 parent 19d61d7 commit 1e8fd36

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ node_modules
22
.DS_Store
33
dist
44
*.log
5+
.idea

src/command/like-rank.ts

+38-5
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ export const likeRank = createCommand('like-rank')
2121
count: +opts.count,
2222
})
2323
})
24+
const maxRetries = 3 // Set the maximum number of retries
25+
const retryDelay = 1000 // Set the delay between retries in milliseconds
2426

2527
export const likeRanking = async ({ top, count }: LikeRankOptions) => {
2628
const [user] = filterUsers()
@@ -33,14 +35,45 @@ export const likeRanking = async ({ top, count }: LikeRankOptions) => {
3335
})
3436

3537
const userMap: Record<string, { user: Entity.User; count: number }> = {}
38+
const postErrorCount: Record<string, number> = {} // Track the error count for each post
3639
for (const [i, post] of posts.entries()) {
3740
spinner.update(`Fetching post (${i + 1} / ${posts.length})`)
41+
const pid = post.id
3842

39-
const users = await post.listLikedUsers()
40-
for (const user of users) {
41-
const id = user.id
42-
if (!userMap[id]) userMap[id] = { user, count: 1 }
43-
else userMap[id].count++
43+
let retryCount = 0
44+
let success = false
45+
46+
while (!success && retryCount < maxRetries) {
47+
try {
48+
const users = await post.listLikedUsers()
49+
for (const user of users) {
50+
const id = user.id
51+
if (!userMap[id]) userMap[id] = { user, count: 1 }
52+
else userMap[id].count++
53+
}
54+
55+
success = true // Mark success to exit the loop
56+
} catch {
57+
retryCount++
58+
postErrorCount[pid] = (postErrorCount[pid] || 0) + 1
59+
60+
if (retryCount < maxRetries) {
61+
await new Promise((resolve) => setTimeout(resolve, retryDelay)) // Wait for the specified delay
62+
}
63+
}
64+
}
65+
66+
if (!success) {
67+
console.error(
68+
`Failed to fetch liked users for post ${
69+
i + 1
70+
} after ${maxRetries} attempts.`,
71+
)
72+
73+
if (postErrorCount[pid] >= 3) {
74+
console.error(`Exiting due to repeated failures for post ${pid}`)
75+
process.exit(1) // Exit the process with an error code
76+
}
4477
}
4578
}
4679

0 commit comments

Comments
 (0)