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
65
66
67
68
69
70
71
72
use crate::node_interface::{NodeError, NodeInterface, Result};
use crate::JsonString;
use json::JsonValue;
use reqwest::blocking::{RequestBuilder, Response};
use reqwest::header::{HeaderValue, CONTENT_TYPE};
impl NodeInterface {
pub fn get_node_api_header(&self) -> HeaderValue {
match HeaderValue::from_str(&self.api_key) {
Ok(k) => k,
_ => HeaderValue::from_static("None"),
}
}
pub fn set_req_headers(&self, rb: RequestBuilder) -> RequestBuilder {
rb.header("accept", "application/json")
.header("api_key", self.get_node_api_header())
.header(CONTENT_TYPE, "application/json")
}
pub fn send_get_req(&self, endpoint: &str) -> Result<Response> {
let url = self.node_url().to_owned() + endpoint;
let client = reqwest::blocking::Client::new().get(&url);
self.set_req_headers(client)
.send()
.map_err(|_| NodeError::NodeUnreachable)
}
pub fn send_post_req(&self, endpoint: &str, body: String) -> Result<Response> {
let url = self.node_url().to_owned() + endpoint;
let client = reqwest::blocking::Client::new().post(&url);
self.set_req_headers(client)
.body(body)
.send()
.map_err(|_| NodeError::NodeUnreachable)
}
pub fn parse_response_to_json(&self, resp: Result<Response>) -> Result<JsonValue> {
let text = resp?.text().map_err(|_| {
NodeError::FailedParsingNodeResponse(
"Node Response Not Parseable into Text.".to_string(),
)
})?;
let json = json::parse(&text).map_err(|_| NodeError::FailedParsingNodeResponse(text))?;
Ok(json)
}
pub fn use_json_endpoint_and_check_errors(
&self,
endpoint: &str,
json_body: &JsonString,
) -> Result<JsonValue> {
let res = self.send_post_req(endpoint, json_body.clone());
let res_json = self.parse_response_to_json(res)?;
let error_details = res_json["detail"].to_string().clone();
if error_details != "null" {
return Err(NodeError::BadRequest(error_details));
}
Ok(res_json)
}
}