arangors_graph_exporter/
request.rs

1use crate::errors::GraphLoaderError;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Serialize, Deserialize)]
5#[serde(rename_all = "camelCase")]
6struct ArangoDBError {
7    error: bool,
8    error_num: i32,
9    error_message: String,
10    code: i32,
11}
12
13// This function handles an HTTP response from ArangoDB, including
14// connection errors, bad status codes and body parsing. The template
15// type is the type of the expected body in the good case.
16pub async fn handle_arangodb_response_with_parsed_body<T>(
17    resp: reqwest_middleware::Result<reqwest::Response>,
18    expected_code: reqwest::StatusCode,
19) -> Result<T, GraphLoaderError>
20where
21    T: serde::de::DeserializeOwned,
22{
23    let resp = resp.map_err(GraphLoaderError::RequestError)?; // Convert reqwest::Error to GraphLoaderError::RequestError
24
25    let status = resp.status();
26    if status != expected_code {
27        let arango_error = resp.json::<ArangoDBError>().await.map_err(|err| {
28            GraphLoaderError::ParseError(format!("Error parsing response body: {}", err))
29        })?;
30
31        return Err(GraphLoaderError::ArangoDBError(
32            arango_error.error_num,
33            arango_error.error_message,
34            status,
35        ));
36    }
37
38    resp.json::<T>().await.map_err(|err| {
39        GraphLoaderError::ParseError(format!("Error parsing response body: {}", err))
40    })
41}
42
43// This function handles an empty HTTP response from ArangoDB, including
44// connection errors and bad status codes.
45pub async fn handle_arangodb_response(
46    resp: reqwest_middleware::Result<reqwest::Response>,
47    code_test: fn(code: reqwest::StatusCode) -> bool,
48) -> Result<reqwest::Response, String> {
49    if let Err(err) = resp {
50        return Err(err.to_string());
51    }
52    let resp = resp.unwrap();
53    handle_arangodb_req_response(resp, code_test).await
54}
55
56async fn handle_arangodb_req_response(
57    resp: reqwest::Response,
58    code_test: fn(code: reqwest::StatusCode) -> bool,
59) -> Result<reqwest::Response, String> {
60    let status = resp.status();
61    if !code_test(status) {
62        let err = resp.json::<ArangoDBError>().await;
63        match err {
64            Err(e) => {
65                return Err(format!(
66                    "Could not parse error body, error: {}, status code: {:?}",
67                    e, status,
68                ));
69            }
70            Ok(e) => {
71                return Err(format!(
72                    "Error code: {}, message: {}, HTTP code: {}",
73                    e.error_num, e.error_message, e.code
74                ));
75            }
76        }
77    }
78    Ok(resp)
79}