【发布时间】:2018-10-16 19:51:51
【问题描述】:
我的 Node.js 应用程序中有两个函数:
retrieveIssues: function(githubAppId, pemFilePath, repoOrg, repoName, callback) {
const octokit = require('@octokit/rest')();
let data = null;
gitInstallationAccessToken.genInstallationAccessToken(githubAppId, pemFilePath, (installationAccessToken) => {
octokit.authenticate({
type: 'app',
token: `${installationAccessToken}`
});
async function paginate(method) {
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue" + " state:open",
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);
});
});
}
retrieveEnerpriseIssues: function(repoOrg, repoName, callback) {
const octokit = require('@octokit/rest')({
baseUrl: config.githubEnterprise.baseUrl
});
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" + " label:sdk" + " state:open",
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);
});
}
}
第一个访问公共 GitHub,第二个访问私有 Github。虽然有一些非常明显的差异(身份验证类型和传递的参数数量等),但它们非常相似。我想知道是否可以将这些重构为单个函数,或者这是否是一个好主意。如果可能并且可以改进我的代码,这是如何完成的?
【问题讨论】:
-
有什么问题?只需结合这些功能添加一些条件...
-
在使用 Promise 和/或
async/await时不要使用callback参数!只是return那个paginate(octokit.search.issues);。
标签: javascript node.js function refactoring