1use crate::resources::auth::token::get_access_token;
2use reqwest::blocking::{Client, Response};
3use serde_json::Value;
4use std::error::Error;
5
6pub struct GraphClient {
7 client: Client,
8 access_token: String,
9 base_url: String,
10}
11
12impl GraphClient {
13 pub fn new(
15 client_id: &str,
16 client_secret: &str,
17 tenant_id: &str,
18 beta: bool,
19 ) -> Result<Self, Box<dyn Error>> {
20 let base_url = if beta {
21 crate::constants::GRAPH_URL_BETA
22 } else {
23 crate::constants::GRAPH_URL
24 }
25 .to_string();
26
27 let access_token = get_access_token(client_id, client_secret, tenant_id)?;
28
29 Ok(GraphClient {
30 client: Client::new(),
31 access_token,
32 base_url,
33 })
34 }
35
36 pub fn get_http_client(&self) -> &Client {
38 &self.client
39 }
40
41 pub fn get_access_token(&self) -> &str {
43 &self.access_token
44 }
45
46 pub fn get(&self, path: &str) -> Result<Value, Box<dyn Error>> {
48 let url = format!("{}{}", self.base_url, path);
49 let res = self
50 .client
51 .get(&url)
52 .bearer_auth(&self.access_token)
53 .send()?
54 .json()?;
55 Ok(res)
56 }
57
58 pub fn post_raw(&self, path: &str, body: Value) -> Result<Response, Box<dyn Error>> {
60 let url = format!("{}{}", self.base_url, path);
61 let res = self
62 .client
63 .post(&url)
64 .bearer_auth(&self.access_token)
65 .json(&body)
66 .send()?;
67 Ok(res)
68 }
69
70 pub fn post(&self, path: &str, body: Value) -> Result<Value, Box<dyn Error>> {
72 let url = format!("{}{}", self.base_url, path);
73 let res = self
74 .client
75 .post(&url)
76 .bearer_auth(&self.access_token)
77 .json(&body)
78 .send()?
79 .json()?;
80 Ok(res)
81 }
82
83 pub fn delete(&self, path: &str) -> Result<Response, Box<dyn Error>> {
85 let url = format!("{}{}", self.base_url, path);
86 let res = self
87 .client
88 .delete(&url)
89 .bearer_auth(&self.access_token)
90 .send()?;
91 Ok(res)
92 }
93
94 pub fn patch(&self, path: &str, body: Value) -> Result<Value, Box<dyn Error>> {
96 let url = format!("{}{}", self.base_url, path);
97 let res = self
98 .client
99 .patch(&url)
100 .bearer_auth(&self.access_token)
101 .json(&body)
102 .send()?
103 .json()?;
104 Ok(res)
105 }
106}