Coverage for api.py : 100%
Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3from types import SimpleNamespace
4from typing import TYPE_CHECKING
6from returns.pipeline import flow
7from returns.pointfree import alt
9from jph import JPHClient
11if TYPE_CHECKING:
12 from typing import Callable, Optional
14 from requests.models import Response
15 from returns.result import Result
17 from jph import Post
20class Api:
21 """This "Application's" API (intentionally minimal to satisfy requirements)"""
23 def __init__(self, client: Optional[JPHClient] = None):
24 # NOTE: This is here so we can inject a mock client
25 self._client = client or JPHClient()
27 def _gen_flow(
28 self, func: Callable[[], Result[Response, Exception]]
29 ) -> Result[Response, Exception]:
30 """Generate a new returns flow with a default handler for client errors
32 Args:
33 func (Callable[[], Result[Response, Exception]]): An action that returns a returns container
35 Returns:
36 Result[Response, Exception]: Represents either a Success or an Exception
37 """
38 handle_error: Callable[[Exception], None] = lambda error: print(
39 [
40 "The JPH client threw an error, check the exception to see what went wrong",
41 error,
42 ]
43 )
45 return flow(func(), alt(handle_error))
47 def createPostRequest(self, new_post: Post) -> Response:
48 """Creates a post and returns a Response unless the client fails
50 Args:
51 new_post (Post): A new Post to create
53 Returns:
54 Response: A regular requests.Response object
55 """
56 return self._gen_flow(lambda: self._client.post("posts", new_post)).unwrap()
58 def deletePostRequest(self, post_id: int) -> Response:
59 """Deletes a post and returns a Response unless the client fails
61 Args:
62 post_id (int): The identifier of the Post you wish to delete
64 Returns:
65 Response: A regular requests.Response object
66 """
67 return self._gen_flow(lambda: self._client.delete("posts", post_id)).unwrap()
69 def getPost(self, id: int) -> Post:
70 """Gets a single Post, provided that it exists. Returns the actual Entity and not a Response
72 Args:
73 id (int): The identifier of the Post you would like
75 Returns:
76 Post: The actual Post
77 """
78 return (
79 self._gen_flow(lambda: self._client.get("posts", id))
80 .unwrap()
81 .json(object_hook=lambda data: SimpleNamespace(**data))
82 )