Local-osu-Server / osu_client_server

0 stars 0 forks source link

better error handling for `api.login` #3

Closed github-actions[bot] closed 2 months ago

github-actions[bot] commented 2 months ago

https://github.com/Local-osu-Server/osu_client_server/blob/dd11984f413e466d65f48865301b1d37afb94e08/adapters/api.py#L37


from typing import TypedDict

from httpx import AsyncClient

BASE_API_URL = "http://localhost:5000/api/v1"

http_client = AsyncClient()

class LoginError(Exception):
    pass

class LoginProfile(TypedDict):
    user_id: int
    username: str

class LoginSession(TypedDict):
    current_osu_token: str
    current_user_id: int
    current_packet_queue: list[dict]  # TODO: typedict the packets

class LoginResponse(TypedDict):
    message: str
    profile: LoginProfile
    session: LoginSession

async def login(username: str) -> LoginResponse:
    response = await http_client.post(
        url=f"{BASE_API_URL}/bancho/login", json={"username": username}
    )

    if response.status_code >= 400:
        # TODO: better error handling for `api.login`
        raise LoginError(f"Failed to login: {response.text}")

    # TODO: typedict the response
    return response.json()

class ProfileResponse(TypedDict):
    user_id: int
    username: str
    accuracy: float
    play_count: int
    total_score: int
    pp: int

async def get_profile(
    user_id: int | None = None,
    username: str | None = None,
) -> ProfileResponse:
    response = await http_client.get(
        url=f"{BASE_API_URL}/profile/",
        params={"user_id": user_id, "username": username},
    )

    if response.status_code >= 400:
        # TODO: better error handling for `api.get_user_stats`
        raise Exception(f"Failed to get user stats: {response.text}")

    return response.json()

class RankFromPPResponse(TypedDict):
    rank: int
    pp: float

async def get_rank(pp: int) -> RankFromPPResponse:
    response = await http_client.get(
        url=f"{BASE_API_URL}/utils/get_rank_from_pp",
        params={"pp": pp},
    )

    if response.status_code >= 400:
        # TODO: better error handling for `api.get_rank`
        raise Exception(f"Failed to get rank: {response.text}")

    return response.json()
github-actions[bot] commented 2 months ago

Closed in 7bba76d62b6dcae54cd8bd1e474a9c8ffa653e9d