sui_gql_client/
reqwest.rs1use cynic::Operation;
2use cynic::http::CynicReqwestError;
3use cynic::serde::Serialize;
4use serde_json::Value as Json;
5
6use crate::RawClient;
7
8#[derive(Clone, Debug)]
10pub struct ReqwestClient {
11 client: reqwest::Client,
12 endpoint: String,
13}
14
15impl ReqwestClient {
16 pub const fn new(client: reqwest::Client, endpoint: String) -> Self {
17 Self { client, endpoint }
18 }
19
20 pub fn new_default(endpoint: impl Into<String>) -> Self {
22 Self {
23 client: reqwest::Client::new(),
24 endpoint: endpoint.into(),
25 }
26 }
27}
28
29impl RawClient for ReqwestClient {
30 type Error = CynicReqwestError;
31
32 async fn run_graphql_raw<Query, Vars>(
33 &self,
34 operation: Operation<Query, Vars>,
35 ) -> Result<Json, Self::Error>
36 where
37 Vars: Serialize + Send,
38 {
39 let http_result = self
40 .client
41 .post(&self.endpoint)
42 .json(&operation)
43 .send()
44 .await;
45 deser_gql(http_result).await
46 }
47}
48
49async fn deser_gql(
50 response: Result<reqwest::Response, reqwest::Error>,
51) -> Result<Json, CynicReqwestError> {
52 let response = match response {
53 Ok(response) => response,
54 Err(e) => return Err(CynicReqwestError::ReqwestError(e)),
55 };
56
57 let status = response.status();
58 if !status.is_success() {
59 let text = response.text().await;
60 let text = match text {
61 Ok(text) => text,
62 Err(e) => return Err(CynicReqwestError::ReqwestError(e)),
63 };
64
65 let Ok(deserred) = serde_json::from_str(&text) else {
66 let response = CynicReqwestError::ErrorResponse(status, text);
67 return Err(response);
68 };
69
70 Ok(deserred)
71 } else {
72 let json = response.json().await;
73 json.map_err(CynicReqwestError::ReqwestError)
74 }
75}