Last active
April 12, 2021 09:48
-
-
Save mjroeleveld/d33cfc30bafaf8802596103cf19842d8 to your computer and use it in GitHub Desktop.
Iterator that loops over Github GraphQL API result using cursor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getOctokit } from '@actions/github'; | |
import { GraphQlQueryResponseData } from '@octokit/graphql'; | |
const MAX_PAGE_SIZE = 100; | |
export interface IterableListSearch<Iterable> { | |
nodes: Iterable[]; | |
pageInfo: PageInfo; | |
} | |
export interface IterableListQuery<Iterable> { | |
edges: Array<{ | |
node: Iterable; | |
}>; | |
pageInfo: PageInfo; | |
} | |
export type IterableList<Iterable> = | |
| IterableListQuery<Iterable> | |
| IterableListSearch<Iterable>; | |
export async function* makeGraphqlIterator<IterableData>( | |
octokit: ReturnType<typeof getOctokit>, | |
query: string, | |
parameters: object, | |
extractListFunction: ( | |
response: GraphQlQueryResponseData, | |
) => IterableList<IterableData> | undefined, | |
): AsyncGenerator<IterableData> { | |
let cursor: string | undefined = undefined; | |
let hasNextPage: boolean = true; | |
const { pageSize = MAX_PAGE_SIZE }: { pageSize?: number } = parameters; | |
while (hasNextPage) { | |
const response = await octokit.graphql<GraphQlQueryResponseData>(query, { | |
...parameters, | |
endCursor: cursor, | |
pageSize, | |
}); | |
const list = extractListFunction(response); | |
if (list === undefined) { | |
return; | |
} | |
cursor = list.pageInfo.endCursor; | |
hasNextPage = list.pageInfo.hasNextPage; | |
let iterables: IterableData[] | undefined = undefined; | |
if ('edges' in list) { | |
iterables = list.edges.map( | |
(edge: { node: IterableData }): IterableData => edge.node, | |
); | |
} else if ('nodes' in list) { | |
iterables = list.nodes; | |
} else { | |
throw new Error('unexpected list format'); | |
} | |
for (const iterable of iterables) { | |
yield iterable; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use it like: