Skip to content

Instantly share code, notes, and snippets.

@ryo-endo
Last active May 25, 2020 13:03
Show Gist options
  • Save ryo-endo/5be03a253a1be41415c8e307891e4bec to your computer and use it in GitHub Desktop.
Save ryo-endo/5be03a253a1be41415c8e307891e4bec to your computer and use it in GitHub Desktop.
Node.jsでGitHubAPIv4を叩くサンプル(ページネーションあり) / call GitHub API v4 with pagination.
//
// Node.jsでGitHubAPIv4を叩くサンプル(ページネーションあり)
//
const https = require('https');
const options = {
method: 'POST',
headers: {
'Authorization': 'bearer ' + process.env.GITHUB_TOKEN,
'Content-type': 'application/json',
'user-agent': 'node.js'
}
};
// GitHubAPIv4のクエリを生成する
const buildQuery = (endCursor) => {
// 文字列の場合はダブルクォーテーションで囲む必要がある
if (endCursor != null) endCursor = '"' + endCursor + '"';
const query = `
query{
repository(name: "ec-cube", owner: "EC-CUBE") {
pullRequests(first: 10, after: ${endCursor}, orderBy: {field: CREATED_AT, direction: ASC}, states: OPEN) {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
number
title
url
}
cursor
}
}
}
}`;
return query;
};
// APIからデータを取得する
const fetchPullRequests = (endCursor, output) => {
return new Promise((resolve) => {
const req = https.request('https://api.github.com/graphql', options, (res) => {
const data = [];
res.on('data', (d) => {
data.push(d);
});
res.on('end', () => {
const buf = Buffer.concat(data);
output(buf);
const jsonObject = JSON.parse(buf);
let hasNextPage = jsonObject.data.repository.pullRequests.pageInfo.hasNextPage;
let endCursor = hasNextPage ? jsonObject.data.repository.pullRequests.pageInfo.endCursor : null;
resolve(endCursor);
});
}).on('error', (e) => {
console.error(e);
});
const query = buildQuery(endCursor);
req.write(JSON.stringify({query}));
req.end();
}).then((endCursor) => {
if (endCursor == null) return;
return fetchPullRequests(endCursor, output);
});
};
// 出力処理
const output = (data) => {
console.log('%s', data);
};
fetchPullRequests(null, output).then();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment