Skip to content

Instantly share code, notes, and snippets.

@froi
Last active July 8, 2020 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save froi/6950d2d9623af4d488414696472b7471 to your computer and use it in GitHub Desktop.
Save froi/6950d2d9623af4d488414696472b7471 to your computer and use it in GitHub Desktop.
Quick example of how to use a async generator to get a repository's labels
const { Octokit } = require('@octokit/rest');
const { throttling } = require('@octokit/plugin-throttling');
const OctokitThrottling = Octokit.plugin(throttling);
const octokit = new OctokitThrottling({
auth: "your-token",
throttle: {
onRateLimit: (retryAfter, options) => {
octokit.log.warn(
`Request quota exhausted for request ${options.method} ${options.url}`
);
if (options.request.retryCount === 0) {
// only retries once
console.log(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
onAbuseLimit: (retryAfter, options) => {
// does not retry, only logs a warning
octokit.log.warn(
`Abuse detected for request ${options.method} ${options.url}`
);
},
},
});
async function* getLabels(owner, repoName) {
let hasNextPage = true;
let cursor = null;
while(hasNextPage) {
const {repository} = await octokit.graphql(`
query($cursor: String, $owner: String!, $name: String!) {
repository(owner:$owner, name:$name) {
labels(first: 5, after: $cursor) {
nodes {
id
name
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
`,
{
cursor,
owner,
name: repoName
}
);
for (let label of repository.labels.nodes) {
yield label;
}
hasNextPage = repository.labels.pageInfo.hasNextPage;
cursor = repository.labels.pageInfo.endCursor;
}
}
(async () => {
let generator = getLabels("froi", "horas");
for await( let labels of generator) {
console.log(labels.name);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment