33import requests
44
55from . import defaults
6- from .exceptions import ResponseJsonError
6+ from .exceptions import ApiRequestError , ResponseJsonError
77from .model import Gitmoji , Guide
88
99
10- def fetch_guide () -> Guide :
10+ def fetch_guide (* , use_backup : bool = False ) -> Guide :
1111 """Fetch the Gitmoji guide from the official Gitmoji API.
1212
1313 This function sends a GET request to the Gitmoji API to retrieve the current state
1414 of the Gitmoji guide. If the request is successful and contains the expected JSON
1515 data, a `Guide` object is returned. If the expected JSON data is not present, a
16- `ResponseJsonError` is raised. In case of an HTTP error during the request (e.g.,
17- connection error, timeout), the function falls back to loading a local copy of the
18- Gitmoji guide.
16+ `ResponseJsonError` is raised. In case of an HTTP error during the request
17+ (e.g., connection error, timeout), and if `use_backup` is set to `True`, the function
18+ falls back to loading a local copy of the Gitmoji guide. Otherwise, it raises an
19+ `ApiRequestError`.
20+
21+ Args:
22+ use_backup: A flag indicating whether to use a local backup in case of a request
23+ failure. Defaults to `False`.
1924
2025 Returns:
2126 A `Guide` object representing the current state of the Gitmoji API.
2227
2328 Raises:
29+ ApiRequestError: If the API request fails and `use_backup` is `False`.
2430 ResponseJsonError: If the API response doesn't contain the expected JSON data or
2531 if there is an error loading the local backup of the Gitmoji guide.
2632 """
@@ -29,9 +35,12 @@ def fetch_guide() -> Guide:
2935
3036 if (gitmojis_json := response .json ().get (defaults .GITMOJI_API_KEY )) is None :
3137 raise ResponseJsonError
32- except requests .RequestException :
33- with defaults .GITMOJI_API_PATH .open (encoding = "UTF-8" ) as f :
34- gitmojis_json = json .load (f )
38+ except requests .RequestException as exc_info :
39+ if use_backup :
40+ with defaults .GITMOJI_API_PATH .open (encoding = "UTF-8" ) as f :
41+ gitmojis_json = json .load (f )
42+ else :
43+ raise ApiRequestError from exc_info
3544
3645 guide = Guide (gitmojis = [Gitmoji (** gitmoji_json ) for gitmoji_json in gitmojis_json ])
3746
0 commit comments