javascript GitHub API请求获取语言使用

mzaanser  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(157)

我淹没在承诺中,试图从我的GitHub Repos中得到一个我认为很简单的数据。
我所要做的就是找到我在GitHub上的每个存储库中语言使用的百分比。我已经让它工作了,但我很有信心,如果我知道我在做什么,我离正确地或简洁地做它还有很长的路要走。我真的很感激任何关于如何正确地做这件事的反馈,以及可能使用更多最新方法的重构。
这是我到目前为止的代码(可以工作)。忽略我现在输出它的方式,这只是为了概念的证明。

const username = '<GH_USERNAME>' //your username here
const apiUrl = `https://api.github.com/users/${username}/repos`;

fetch(apiUrl)
.then((response) => {
    if (response.ok) {
        return response.json();
    }  
})
.then((data) => {
    languagePromises = [];
    for (let i in data) {
        let repo = data[i];
        if (!repo['fork'] && repo['language']) {
            // console.log(repo['name'], repo['language']);
            let langs = repo['languages_url'];
            languagePromises.push(fetch(langs))
        }
    }
    Promise.all(languagePromises)
    .then((responses) => { 
        let languages = [];
        for (let r of responses) {
            if (r.ok) languages.push(r.json())
        }
        Promise.all(languages)
        .then((resolved) => { 
            let languageTotals = {};
            for (langData of resolved) {
                for (lang in langData) {
                    if (!languageTotals[lang]) {
                        languageTotals[lang] = 0
                    }
                    languageTotals[lang] += (langData[lang]); 
                }
            }
            // console.log(languageTotals);
            let sum = 0;
            for (let l in languageTotals) { sum += languageTotals[l] }
            for (let l in languageTotals) {
                let p = (languageTotals[l] / sum * 100).toFixed(0) + '%';
                document.write(l,' ', p, '<br>');
            }
        });
    });
})
.catch((e) => {
    console.error('Error:', e);
});

就像是说。它的工作,但我基本上是在寻找如何正确地做这件事的建议。

cfh9epnr

cfh9epnr1#

const username = 'octocat'
const apiUrl = `https://api.github.com/users/${username}/repos`;

fetch(apiUrl)
  .then((response) => {
    if (!response.ok) {
      throw new Error('Request failed')
    }
    return response.json();
  })
  .then((repos) => repos.filter(repo => !repo['fork'] && repo['language']).map(repo => fetch(repo['languages_url'])))
  .then(e => Promise.all(e))
  .then((resps) => resps.filter(r => r.ok).map(r => r.json()))
  .then(e => Promise.all(e))
  .then((resolved) => {
    console.log(resolved)
    const languageTotals = {};
    for (const langData of resolved) {
      for (const lang in langData) {
        if (!languageTotals[lang]) {
          languageTotals[lang] = 0
        }
        languageTotals[lang] += (langData[lang]);
      }
    }

    let sum = 0;
    for (const lang of languageTotals) {
      sum += lang
    }
    for (const lang of languageTotals) {
      let p = (lang / sum * 100).toFixed(0) + '%';
      document.write(l, ' ', p, '<br>');
    }

  })
  .catch((e) => {
    console.error('Error:', e);
  });
goqiplq2

goqiplq22#

下面是一个清理/减少大量代码的示例:

const apiUrl = `https://api.github.com/users/${username}/repos`;

fetchRepos(apiUrl)
  .then((data) => {
    return (data
      .filter(repo => !repo.fork && repo.language)
      .map(repo => ghFetchJson(repo.languages_url))
    )
  )
  .then(languageResults => {
    const languageTotals = new Map();
    for (const langData of languageResults) {
      for (const [lang, count] of Object.entries(langData)) {
        languageTotals.set(lang, (languageTotals.get(lang) ?? 0) + count);
      }
    }
    const sum = Array.from(languageTotals).reduce((acc, cur) => acc+cur[0], 0);

    for(const [language, count] of languageTotals) {
      const p = (count / sum * 100).toFixed(0) + '%';
      console.log('%s: %i', language, count);
    }

  });
}).catch((e) => {
    console.error('Error:', e);
});

async function ghFetchJson(url) {

  const res = await fetch(url);
  return res.json();

}

相关问题