Add generic pagination util + use in branch fetch

This commit is contained in:
2018-06-05 18:30:00 +05:30
parent a58a437210
commit 83d35b38ff
+51 -7
View File
@@ -8,14 +8,27 @@ octokit.authenticate({
secret: '2228539a48032f0622d6c12a66f56253d0a30d60', secret: '2228539a48032f0622d6c12a66f56253d0a30d60',
}); });
interface ResponseWithDataArray<T> {
data: T[];
}
interface ResponseWithMetaLink {
meta: {
link: string
};
}
interface ResponseWithPaginationAndMeta<T> extends ResponseWithDataArray<T>, ResponseWithMetaLink {
}
interface ResponseFromGetUserRepo { interface ResponseFromGetUserRepo {
data: RepoFromGetUserRepo[]; data: RepoFromGetUserRepo[];
meta: {}; meta: {};
} }
interface ResponseFromGetBranches { interface ResponseFromGetBranches extends ResponseWithMetaLink {
data: BranchFromGetBranches[]; data: BranchFromGetBranches[];
meta: {};
} }
interface ResponseFromGetRepo { interface ResponseFromGetRepo {
@@ -99,19 +112,50 @@ interface RepoNameWithParentRepo {
interface RepoNameWithBranchesAndParent interface RepoNameWithBranchesAndParent
extends RepoNameWithBranches, extends RepoNameWithBranches,
RepoNameWithParentRepo {} RepoNameWithParentRepo { }
const username = 'bendtherules'; const username = 'bendtherules';
interface ObjectWithPerPage {
per_page?: number;
}
async function paginate<TFirstParam extends ObjectWithPerPage, TDataElement>(
method: (args: TFirstParam) => ResponseWithPaginationAndMeta<TDataElement>,
args: TFirstParam
): Promise<ResponseWithDataArray<TDataElement>> {
// Set per_page
args.per_page = 100;
let response: ResponseWithPaginationAndMeta<TDataElement> = await method(args);
// Concat all data
let { data } = response;
while (octokit.hasNextPage(response)) {
response = await octokit.getNextPage(response);
data = data.concat(response.data);
}
return {
data
};
}
async function fetchRepoNameWithBranches( async function fetchRepoNameWithBranches(
repoName: string repoName: string
): Promise<RepoNameWithBranches> { ): Promise<RepoNameWithBranches> {
const branchesResponse: ResponseFromGetBranches = await octokit.repos.getBranches( const params: rest.ReposGetBranchesParams = {
{
owner: username, owner: username,
repo: repoName, repo: repoName,
per_page: 10, // change this };
}
const branchesResponse: ResponseWithDataArray<BranchFromGetBranches> =
await paginate(
(tmpFirstParam: rest.ReposGetBranchesParams): ResponseFromGetBranches => {
return octokit.repos.getBranches(tmpFirstParam) as any as ResponseFromGetBranches;
},
params
); );
return { return {