@@ -21,6 +21,8 @@ export const likeRank = createCommand('like-rank')
21
21
count : + opts . count ,
22
22
} )
23
23
} )
24
+ const maxRetries = 3 // Set the maximum number of retries
25
+ const retryDelay = 1000 // Set the delay between retries in milliseconds
24
26
25
27
export const likeRanking = async ( { top, count } : LikeRankOptions ) => {
26
28
const [ user ] = filterUsers ( )
@@ -33,14 +35,45 @@ export const likeRanking = async ({ top, count }: LikeRankOptions) => {
33
35
} )
34
36
35
37
const userMap : Record < string , { user : Entity . User ; count : number } > = { }
38
+ const postErrorCount : Record < string , number > = { } // Track the error count for each post
36
39
for ( const [ i , post ] of posts . entries ( ) ) {
37
40
spinner . update ( `Fetching post (${ i + 1 } / ${ posts . length } )` )
41
+ const pid = post . id
38
42
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
+ }
44
77
}
45
78
}
46
79
0 commit comments