import { NextApiRequest , NextApiResponse } from 'next' ; import axios from 'axios' ; import { getPageGithubSources } from './../../../src/services/sanity/index' ; import { GithubRepository } from '../../../src/types/global' ; const sortReposByStars = ( repositories ) : GithubRepository [ ] => { return repositories . sort ( ( repoA , repoB ) => { if ( repoA . stars > repoB . stars ) return 1 ; return - 1 ; } ) . reverse ( ) ; } ; const defineRepositories = ( repositories ) : GithubRepository [ ] => { const repos = repositories . map ( ( repo ) => { return { name : repo . name , url : repo . html_url , description : repo . description , lang : repo . language , stars : repo . stargazers_count , forks : repo . forks_count } ; } ) ; return repos ; } ; const filterRepositories = async ( sources ) : Promise < GithubRepository [ ] > => { const repositories = [ ] ; for await ( const source of sources ) { const { data } = await axios . get ( `${ source }?per_page=100` ) ; repositories . push ( ... data ) ; } return defineRepositories ( repositories ) ; } ; const getRepositories = async ( req , res ) : Promise < void > => { const sources = await getPageGithubSources ( ) ; try { let repositories = await filterRepositories ( sources [ 0 ] . links ) ; repositories = sortReposByStars ( repositories ) ; res . status ( 200 ) . send ( { repositories } ) ; } catch ( error ) { res . status ( 500 ) . send ( error ) ; } } ; export default getRepositories ;