ergo_node_interface/
requests.rs

1use crate::node_interface::{NodeError, NodeInterface, Result};
2use crate::JsonString;
3use json::JsonValue;
4use reqwest::blocking::{RequestBuilder, Response};
5use reqwest::header::{HeaderValue, CONTENT_TYPE};
6
7impl NodeInterface {
8    /// Builds a `HeaderValue` to use for requests with the api key specified
9    pub fn get_node_api_header(&self) -> HeaderValue {
10        match HeaderValue::from_str(&self.api_key) {
11            Ok(k) => k,
12            _ => HeaderValue::from_static("None"),
13        }
14    }
15
16    /// Sets required headers for a request
17    pub fn set_req_headers(&self, rb: RequestBuilder) -> RequestBuilder {
18        rb.header("accept", "application/json")
19            .header("api_key", self.get_node_api_header())
20            .header(CONTENT_TYPE, "application/json")
21    }
22
23    /// Sends a GET request to the Ergo node
24    pub fn send_get_req(&self, endpoint: &str) -> Result<Response> {
25        let url = self
26            .url
27            .join(endpoint)
28            .map_err(|e| NodeError::InvalidUrl(e.to_string()))?;
29        let client = reqwest::blocking::Client::new().get(url);
30        self.set_req_headers(client)
31            .send()
32            .map_err(|_| NodeError::NodeUnreachable)
33    }
34
35    /// Sends a POST request to the Ergo node
36    pub fn send_post_req(&self, endpoint: &str, body: String) -> Result<Response> {
37        let url = self
38            .url
39            .join(endpoint)
40            .map_err(|e| NodeError::InvalidUrl(e.to_string()))?;
41        let client = reqwest::blocking::Client::new().post(url);
42        self.set_req_headers(client)
43            .body(body)
44            .send()
45            .map_err(|_| NodeError::NodeUnreachable)
46    }
47
48    /// Parses response from node into JSON
49    pub fn parse_response_to_json(&self, resp: Result<Response>) -> Result<JsonValue> {
50        let text = resp?.text().map_err(|_| {
51            NodeError::FailedParsingNodeResponse(
52                "Node Response Not Parseable into Text.".to_string(),
53            )
54        })?;
55        let json = json::parse(&text).map_err(|_| NodeError::FailedParsingNodeResponse(text))?;
56        Ok(json)
57    }
58
59    /// General function for submitting a Json String body to an endpoint
60    /// which also returns a `JsonValue` response.
61    pub fn use_json_endpoint_and_check_errors(
62        &self,
63        endpoint: &str,
64        json_body: &JsonString,
65    ) -> Result<JsonValue> {
66        let res = self.send_post_req(endpoint, json_body.to_string());
67
68        let res_json = self.parse_response_to_json(res)?;
69        let error_details = res_json["detail"].to_string();
70
71        // Check if send tx request failed and returned error json
72        if error_details != "null" {
73            return Err(NodeError::BadRequest(error_details));
74        }
75
76        Ok(res_json)
77    }
78}