File size: 2,009 Bytes
4c83ab6
780bb45
4c83ab6
 
 
0a367ef
4c83ab6
 
 
780bb45
 
 
 
 
 
 
 
4c83ab6
 
 
 
 
 
 
 
 
 
 
 
 
 
780bb45
4c83ab6
 
 
 
 
 
780bb45
4c83ab6
 
 
 
 
 
780bb45
4c83ab6
 
 
 
 
 
780bb45
4c83ab6
 
 
 
 
 
780bb45
4c83ab6
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import asyncio
import logging

import httpx

from app.lib.graph.auth import GraphAuthProvider

_BASE_URL = "https://graph.microsoft.com/v1.0"

logger = logging.getLogger(__name__)


def _raise_with_detail(resp: httpx.Response) -> None:
    if resp.is_error:
        logger.error("Graph %s %s → %s: %s", resp.request.method, resp.request.url, resp.status_code, resp.text)
    resp.raise_for_status()


class GraphClient:
    def __init__(self, auth: GraphAuthProvider) -> None:
        self._auth = auth
        self._client = httpx.AsyncClient(timeout=30.0)

    async def _headers(self) -> dict[str, str]:
        token = await asyncio.to_thread(self._auth.get_access_token)
        return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}

    async def get(self, path: str, params: dict | None = None) -> dict:
        resp = await self._client.get(
            f"{_BASE_URL}{path}", headers=await self._headers(), params=params
        )
        _raise_with_detail(resp)
        return resp.json()

    async def get_raw(self, path: str) -> bytes:
        resp = await self._client.get(
            f"{_BASE_URL}{path}", headers=await self._headers()
        )
        _raise_with_detail(resp)
        return resp.content

    async def post(self, path: str, body: dict) -> dict:
        resp = await self._client.post(
            f"{_BASE_URL}{path}", headers=await self._headers(), json=body
        )
        _raise_with_detail(resp)
        return resp.json()

    async def patch(self, path: str, body: dict) -> dict:
        resp = await self._client.patch(
            f"{_BASE_URL}{path}", headers=await self._headers(), json=body
        )
        _raise_with_detail(resp)
        return resp.json()

    async def delete(self, path: str) -> None:
        resp = await self._client.delete(
            f"{_BASE_URL}{path}", headers=await self._headers()
        )
        _raise_with_detail(resp)

    async def aclose(self) -> None:
        await self._client.aclose()