cod_client/general_requests/
post.rs1use std::fmt::Debug;
2
3use reqwest::header;
4use reqwest::Url;
5use serde::de::DeserializeOwned;
6use serde::Serialize;
7
8use crate::CodebergClient;
9
10impl CodebergClient {
11 pub async fn post_body<B: serde::Serialize, T: DeserializeOwned + Debug>(
12 &self,
13 api_endpoint: Url,
14 body: B,
15 ) -> anyhow::Result<T> {
16 self.post_query_body::<[(); 0], B, T>(api_endpoint, body, [])
17 .await
18 }
19
20 pub async fn post_query_body<Q: Serialize, B: Serialize, T: DeserializeOwned + Debug>(
21 &self,
22 api_endpoint: Url,
23 body: B,
24 query: Q,
25 ) -> anyhow::Result<T> {
26 tracing::debug!(
27 "Making POST call. API endpoint: {:?}",
28 api_endpoint.as_str()
29 );
30 let body_str = serde_json::to_string(&body)?;
31 tracing::debug!("POST Body: {body_str}");
32 let response = self
33 .post(api_endpoint.clone())
34 .query(&query)
35 .header(
36 header::CONTENT_TYPE,
37 "application/json".parse::<header::HeaderValue>()?,
38 )
39 .body(body_str)
40 .send()
41 .await?;
42 let status = response.status();
43 tracing::debug!("Response Status: {status:?}");
44 if !status.is_success() {
45 let body_str = serde_json::to_string(&body)?;
46 let response = self
47 .post(api_endpoint)
48 .query(&query)
49 .header(
50 header::CONTENT_TYPE,
51 "application/json".parse::<header::HeaderValue>()?,
52 )
53 .body(body_str)
54 .send()
55 .await?;
56 let text = response.text().await?;
57 tracing::debug!("Failed POST: {text}");
58 }
59 let json_response = response.json().await?;
60 tracing::debug!("Response: {:?}", json_response);
61 Ok(json_response)
62 }
63}