When you send a GET
request to , you will receive the repositories owned by the user benawad
. However, GitHub limits the number of repositories returned to 30.
The user benawad
currently has 246 repositories as of today (14/08/2021).
In order to workaround this limitation, you can make a GET request with additional parameters. GitHub uses pagination in its API, so you need to specify the desired page and the number of repositories per page in the URL.
Your modified GET
request should resemble the following:
However, GitHub restricts the maximum number of repositories per page to 100. Therefore, your modified GET
request will only return 100 repos instead of the total 246 repositories owned by the user benawad
.
I have implemented the code below in my Angular service to fetch all repositories from multiple pages:
public getUserRepos(user: string): Observable<RepositoryI[]> {
return new Observable((subscriber: Subscriber<RepositoryI[]>) => {
this.getUserData(user).subscribe((data: UserI) => {
const pages: number = Math.ceil(data.public_repos / 100);
for (let i = 1; i <= pages; i++) {
this.http
.get(`https://api.github.com/users/${user}/repos?page=${i}&per_page=100`)
.subscribe((data: RepositoryI[]) => {
subscriber.next(data);
});
}
});
});
}
To handle when the Observable has completed emitting values, I subscribe to it in my component with the following code snippet:
this.userService.getUserRepos(id).subscribe((repos)=>{
this.repositories.push(...repos);
})
An issue arises where I lack control over determining when the Observable has finished emitting values. In my component, I want to execute a function when the Observable is complete.
I attempted the approach below:
public getUserRepos(user: string): Observable<RepositoryI[]> {
return new Observable((subscriber: Subscriber<RepositoryI[]>) => {
this.getUserData(user).subscribe((data: UserI) => {
const pages: number = Math.ceil(data.public_repos / 100);
for (let i = 1; i <= pages; i++) {
this.http
.get(`https://api.github.com/users/${user}/repos?page=${i}&per_page=100`)
.subscribe((data: RepositoryI[]) => {
subscriber.next(data);
if(pages == i) subscriber.complete();
});
}
});
});
}
In my component, I do the following:
this.userService.getUserRepos(id).subscribe(
(repos) => {
this.repositories.push(...repos);
},
(err) => {
console.log(err);
},
() => {
console.log(this.repositories);
// The output logs only 46 repositories instead of the expected 246
// I wish to trigger a function here
}
);
The console.log()
statement displays 46 repositories instead of 246. This discrepancy may occur due to prematurely completing the subscriber before fetching all three pages. Even though I call .complete()
within the subscription, there seems to be an error. Can someone guide me on what I might be doing incorrectly? Thank you in advance.