1+ import { calculateGitScore , generateBadges } from "@/lib/score-calculator"
2+
13const GITHUB_TOKEN = process . env . GITHUB_TOKEN || "" ;
24
35interface NextFetchRequestConfig {
@@ -9,6 +11,63 @@ interface ExtendedRequestInit extends RequestInit {
911 next ?: NextFetchRequestConfig ;
1012}
1113
14+ // Cache para scores calculados
15+ const scoreCache = new Map < string , {
16+ score : number ;
17+ badges : any [ ] ;
18+ timestamp : number ;
19+ userDataHash : string ;
20+ } > ( )
21+
22+ const CACHE_DURATION = 1000 * 60 * 60 * 24 // 24 horas
23+
24+ // Função para gerar hash dos dados do usuário (para detectar mudanças)
25+ function generateUserDataHash ( userData : any , reposData : any [ ] ) : string {
26+ const hashData = {
27+ followers : userData . followers ,
28+ public_repos : userData . public_repos ,
29+ public_gists : userData . public_gists ,
30+ stars : reposData . reduce ( ( acc : number , repo : any ) => acc + repo . stargazers_count , 0 ) ,
31+ forks : reposData . reduce ( ( acc : number , repo : any ) => acc + repo . forks_count , 0 ) ,
32+ lastPush : reposData . length > 0 ? reposData [ 0 ] . pushed_at : null ,
33+ }
34+ return JSON . stringify ( hashData )
35+ }
36+
37+ // Função para obter score com cache
38+ export async function getCachedScore ( username : string ) : Promise < { score : number ; badges : any [ ] } > {
39+ const now = Date . now ( )
40+ const userKey = username . toLowerCase ( )
41+
42+ const userData = await fetchGitHubUser ( username )
43+ const reposData = await fetchUserRepos ( username )
44+ const currentHash = generateUserDataHash ( userData , reposData )
45+
46+ // Verificar se existe cache válido
47+ const cached = scoreCache . get ( userKey )
48+ if ( cached &&
49+ ( now - cached . timestamp ) < CACHE_DURATION &&
50+ cached . userDataHash === currentHash ) {
51+ console . log ( `Using cached score for ${ username } ` )
52+ return { score : cached . score , badges : cached . badges }
53+ }
54+
55+ // Calcular novo score
56+ // console.log(`Calculating new score for ${username}`)
57+ const score = calculateGitScore ( userData , reposData )
58+ const badges = generateBadges ( userData , reposData )
59+
60+ // Armazenar no cache
61+ scoreCache . set ( userKey , {
62+ score,
63+ badges,
64+ timestamp : now ,
65+ userDataHash : currentHash
66+ } )
67+
68+ return { score, badges }
69+ }
70+
1271export async function fetchGitHubUser ( username : string ) {
1372 const response = await fetch ( `https://api.github.com/users/${ username } ` , {
1473 headers : {
@@ -103,27 +162,6 @@ export async function fetchPopularDevelopers(location?: string, language?: strin
103162 return response . json ( )
104163}
105164
106- // Função para calcular GitScore baseado nos dados do usuário e repositórios
107- export function calculateGitScore ( user : any , repos : any [ ] ) {
108- const totalStars = repos . reduce ( ( acc , repo ) => acc + repo . stargazers_count , 0 )
109- const totalForks = repos . reduce ( ( acc , repo ) => acc + repo . forks_count , 0 )
110- const publicRepos = user . public_repos || repos . length
111- const followers = user . followers || 0
112- const accountAge = Math . max ( 1 , Math . floor ( ( Date . now ( ) - new Date ( user . created_at ) . getTime ( ) ) / ( 1000 * 60 * 60 * 24 * 365 ) ) )
113-
114- // Cálculo do score baseado em múltiplos fatores
115- const starScore = Math . sqrt ( totalStars ) * 10
116- const forkScore = Math . sqrt ( totalForks ) * 8
117- const repoScore = Math . sqrt ( publicRepos ) * 15
118- const followerScore = Math . sqrt ( followers ) * 12
119- const consistencyBonus = Math . min ( 100 , ( publicRepos / accountAge ) * 20 )
120-
121- const rawScore = starScore + forkScore + repoScore + followerScore + consistencyBonus
122-
123- // Normalizar para uma escala mais intuitiva
124- return Math . round ( rawScore )
125- }
126-
127165// Função para obter rank baseado no score
128166export function getRankFromScore ( score : number ) : string {
129167 if ( score >= 4000 ) return "SS+"
@@ -160,7 +198,7 @@ export async function fetchLeaderboardData(filters: {
160198 fetchUserRepos ( dev . login )
161199 ] )
162200
163- const score = calculateGitScore ( userDetails , repos )
201+ const { score, badges } = await getCachedScore ( dev . login )
164202 const rank = getRankFromScore ( score )
165203
166204 // Filtrar por score se especificado
0 commit comments