过滤通过GitHub API获得的数据

时间:2018-09-13 17:29:50

标签: javascript node.js rest filter github-api

我创建了此函数来获取GitHub问题:

retrieveEnerpriseIssues: function(repoOrg, repoName, callback) { 
  let data = null;

  // token auth
  octokit.authenticate({
    type: 'basic',
    username: config.githubEnterprise.username,
    password: config.githubEnterprise.token
  });

  async function paginate(method) {
    let response = await method({
      q: "repo:" + repoOrg + "/" + repoName + " is:issue",
      per_page: 100
    });
    data = response.data.items;
    var count = 0;
    while (octokit.hasNextPage(response)) {
      count++;
      console.log(`request n°${count}`);
      response = await octokit.getNextPage(response);
      data = data.concat(response.data.items);
    }
    return data;
  }

  paginate(octokit.search.issues)
    .then(data => {
      callback(data);
    })
    .catch(error => {
      console.log(error);
    });
  }

在此函数中调用该函数,以解决问题,将所有不需要的键过滤为json格式,并将其放入我的数据库中。

extractToDb: function() {
  let gitIssues = null;
  for(var i = 0; i < config.githubEnterprise.orgs.length; i++) {
    for(var j = 0; j < config.githubEnterprise.orgs[i].repos.length; j++) {
      gitHubService.retrieveEnerpriseIssues(
        config.githubEnterprise.orgs[i].owner,
        config.githubEnterprise.orgs[i].repos[j].repoName,
        function(data, err) {
          if(err) {
            console.log('err: ', err);
          } else {
            gitIssues = data;
          }
          gitIssues = JSON.stringify(gitIssues);
          gitIssues = JSON.parse(gitIssues);
          let issueFormatForDb = null;
          for(var i = 0; i < gitIssues.length; i++) {
            issueFormatForDb = gitIssues[i];
            const body = '{' +
              '"github_id": "' + issueFormatForDb.id + '",' +
              '"issue_title": "' + issueFormatForDb.title + '",' +
              '"issue_number": "' + issueFormatForDb.number + '",' +
              '"issue_url": "' + issueFormatForDb.url + '",' +
              '"issue_state": "' + issueFormatForDb.state + '"' +  
          '}';
          console.log('Body: ', body);
          getGitHubIssues.postToDb(body);
        }
      });
    }
  }
}

我想通过过滤掉状态为关闭的所有问题来更进一步。该如何完成?应该在我的retrieveEnerpriseIssues函数或extractToDb函数中进行处理吗?

可能的解决方案 我在extractToDb函数中尝试过:

gitIssues = JSON.parse(gitIssues);
gitIssues = _.where(gitIssues, {state: "open"});
let issueFormatForDb = null;

这是最好的解决方案还是有更好的方法?

1 个答案:

答案 0 :(得分:0)

如@givehug所述:

最好使用_.filter或类似

的本机过滤器方法
gitIssues = gitIssues.filter(i => i.state === 'open')

我认为.where在lodash github.com/lodash/lodash/wiki/Deprecations的更高版本中已被弃用。除此之外,一切都很好。

我刚刚意识到可以使用以下方法过滤paginate函数中的状态:

let response = await method({
    q: "repo:" + repoOrg + "/" + repoName + " is:issue" + " label:issue_label" + " state:open",
    per_page: 100
  });