diff --git a/api.py b/api.py index 79a11e1..15277c4 100644 --- a/api.py +++ b/api.py @@ -4,37 +4,21 @@ import httpx class API: headers = {"Accept": "application/vnd.github.v3+json"} - def __init__(self, user_name: str) -> None: - self.user = self.load_user(user_name) - self.user_name = self.user["login"] - self.repos = self.load_repos() # TODO: Check if pagination + def raise_on_4xx_5xx(self, response): + response.raise_for_status() - def _get(self, url: str) -> dict: - """Uses httpx.Client().get to send the appropriate github headers, and return the url""" - with httpx.Client(headers=self.headers) as client: - return client.get(url).json() - - def _get_paged(self, url: str) -> list: + def get(self, url: str) -> list: """Uses httpx.Client().get to send the appropriate github headers, and return the url""" content = [] - with httpx.Client(headers=self.headers) as client: + with httpx.Client(headers=self.headers, event_hooks={'response': [self.raise_on_4xx_5xx]}) as client: while True: resp = client.get(url) - content.extend(resp.json()) + body = resp.json() + if isinstance(body, dict): + # short circuit if not list + return body + content.extend(body) if not resp.links.get('next'): break url = resp.links['next']['url'] return content - - - def load_user(self, user_name: str) -> dict: - """Sets the user object""" - return self._get(f"https://api.github.com/users/{user_name}") - - def load_repo(self, repo_name: str) -> dict: - """Set the repo object""" - return self._get(f"https://api.github.com/repos/{self.user_name}/{repo_name}") - - def load_repos(self) -> dict: - """Set the users repos""" - return self._get_paged(f"https://api.github.com/users/{self.user_name}/repos") diff --git a/cli.py b/cli.py index c51bf42..ed27dc9 100644 --- a/cli.py +++ b/cli.py @@ -7,8 +7,9 @@ import httpx def main(): user_name = Prompt.ask("Username?") gh = GHub() - gh.load_user(user_name=user_name) - print(gh.repos_table()) + success = gh.load_user(user_name=user_name) + if success: + print(gh.repos_table()) diff --git a/ghub.py b/ghub.py index 1eb930a..5ba2cb5 100644 --- a/ghub.py +++ b/ghub.py @@ -2,6 +2,7 @@ from rich.table import Table from rich.prompt import Prompt from rich import print from api import API +import httpx class GHub: @@ -10,9 +11,12 @@ class GHub: def load_user(self, user_name: str) -> None: self.user_name = user_name - self.api = API(self.user_name) - self.user = self.api.user - self.repos = self.api.repos + self.api = API() + try: + self.user = self.api.get(f"https://api.github.com/users/{user_name}") + self.repos = self.api.get(f"https://api.github.com/users/{user_name}/repos") + except httpx.HTTPStatusError as e: + print(e) def repos_trimmed(self) -> list: for repo in self.repos: