1- import type { CachedFetchFunction , CachedFetchResult } from '#shared/utils/fetch-cache-config'
21import { CACHE_MAX_AGE_ONE_DAY } from '#shared/utils/constants'
32
43type GitHubContributorWeek = {
@@ -25,33 +24,40 @@ export default defineCachedEventHandler(
2524 } )
2625 }
2726
28- let cachedFetch : CachedFetchFunction
29- if ( event . context . cachedFetch ) {
30- cachedFetch = event . context . cachedFetch
31- } else {
32- cachedFetch = async < T = unknown > (
33- url : string ,
34- options : Parameters < typeof $fetch > [ 1 ] = { } ,
35- _ttl ?: number ,
36- ) : Promise < CachedFetchResult < T > > => {
37- const data = ( await $fetch < T > ( url , options ) ) as T
38- return { data, isStale : false , cachedAt : null }
39- }
27+ const url = `https://api.github.com/repos/${ owner } /${ repo } /stats/contributors`
28+ const headers = {
29+ 'User-Agent' : 'npmx' ,
30+ 'Accept' : 'application/vnd.github+json' ,
4031 }
4132
33+ const sleep = ( ms : number ) => new Promise ( resolve => setTimeout ( resolve , ms ) )
34+ const maxAttempts = 6
35+ let delayMs = 1000
36+
4237 try {
43- const { data } = await cachedFetch < GitHubContributorStats [ ] > (
44- `https://api.github.com/repos/${ owner } /${ repo } /stats/contributors` ,
45- {
46- headers : {
47- 'User-Agent' : 'npmx' ,
48- 'Accept' : 'application/vnd.github+json' ,
49- } ,
50- } ,
51- CACHE_MAX_AGE_ONE_DAY ,
52- )
53-
54- return Array . isArray ( data ) ? data : [ ]
38+ for ( let attempt = 0 ; attempt < maxAttempts ; attempt += 1 ) {
39+ const response = await $fetch . raw < GitHubContributorStats [ ] > ( url , { headers } )
40+ const status = response . status
41+
42+ if ( status === 200 ) {
43+ return Array . isArray ( response . _data ) ? response . _data : [ ]
44+ }
45+
46+ if ( status === 204 ) {
47+ return [ ]
48+ }
49+
50+ if ( status === 202 ) {
51+ if ( attempt === maxAttempts - 1 ) return [ ]
52+ await sleep ( delayMs )
53+ delayMs = Math . min ( delayMs * 2 , 16_000 )
54+ continue
55+ }
56+
57+ return [ ]
58+ }
59+
60+ return [ ]
5561 } catch {
5662 return [ ]
5763 }
0 commit comments