Skip to content

Commit cc498b7

Browse files
committed
refactor paths v2
1 parent da686cd commit cc498b7

1 file changed

Lines changed: 26 additions & 16 deletions

File tree

ravyapi/api/paths.py

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,31 @@ class BasePath:
2727
The route for the endpoint.
2828
"""
2929

30-
__slots__: tuple[str, ...] = ("_route", "_id")
30+
__slots__: tuple[str, ...] = ("_base_path",)
3131

32-
def __init__(self, route: str, id: int | None = None) -> None:
33-
self._route: str = route
34-
self._id: int | None = id
32+
def __init__(self, base_path: str = "") -> None:
33+
self._base_path = base_path.rstrip("/")
34+
35+
def __str__(self) -> str:
36+
return self._base_path
37+
38+
def __truediv__(self, path: str | int) -> BasePath:
39+
"""Enable path building with / operator."""
40+
return self.__class__(f"{self._base_path}/{path}")
3541

3642
@property
3743
def route(self) -> str:
3844
"""The route for the endpoint."""
39-
return self._route
45+
return self._base_path
4046

4147
@property
4248
def id(self) -> int | None:
43-
return self._id
49+
# extract id from path if it exists
50+
parts = self._base_path.split("/")
51+
for part in reversed(parts):
52+
if part.isdigit():
53+
return int(part)
54+
return None
4455

4556

4657
class Paths:
@@ -56,14 +67,13 @@ class Paths:
5667
A path class for the `tokens` endpoint.
5768
urls : URLs
5869
A path class for the `urls` endpoint.
70+
guilds : Callable[[int], Guilds]
71+
A callable that returns a path class for the `guilds` endpoint.
72+
users : Callable[[int], Users]
73+
A callable that returns a path class for the `users` endpoint.
5974
"""
6075

61-
__slots__: tuple[str, ...] = (
62-
"avatars",
63-
"ksoft",
64-
"tokens",
65-
"urls",
66-
)
76+
__slots__: tuple[str, ...] = ()
6777

6878
@property
6979
def avatars(self) -> Avatars:
@@ -152,7 +162,7 @@ class Guilds(BasePath):
152162
__slots__: tuple[str, ...] = ()
153163

154164
def __init__(self, guild_id: int) -> None:
155-
super().__init__(f"/guilds/{guild_id}", guild_id)
165+
super().__init__(f"/guilds/{guild_id}")
156166

157167

158168
class KSoft(BasePath):
@@ -164,7 +174,7 @@ class KSoft(BasePath):
164174
The route for the endpoint.
165175
"""
166176

167-
__slots__: tuple[str, ...] = ("bans",)
177+
__slots__: tuple[str, ...] = ()
168178

169179
def __init__(self) -> None:
170180
super().__init__("/ksoft")
@@ -234,10 +244,10 @@ class Users(BasePath):
234244
The route for `reputation`.
235245
"""
236246

237-
__slots__: tuple[str, ...] = ("_user_id", "_route")
247+
__slots__: tuple[str, ...] = ()
238248

239249
def __init__(self, user_id: int) -> None:
240-
super().__init__(f"/users/{user_id}", user_id)
250+
super().__init__(f"/users/{user_id}")
241251

242252
@property
243253
def pronouns(self) -> str:

0 commit comments

Comments
 (0)