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
73
74
75
76
77
78
use graphql_client::GraphQLQuery;
use reqwest::{
    blocking::{Client, RequestBuilder},
    header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE},
};

use crate::{config::Config, connect_params::ConnectParams, introspection::IntrospectionResponse};

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "src/graphql/introspection_schema.graphql",
    query_path = "src/graphql/introspection_query.graphql",
    responsive_path = "Serialize",
    variable_derive = "Deserialize"
)]
struct IntrospectionQuery;

pub struct Session;

impl Session {
    pub fn new() -> Self {
        Self {}
    }

    pub fn start(&self, _cfg: &Config, conn: &ConnectParams) -> eyre::Result<RequestBuilder> {
        let client = Client::builder()
            .user_agent("graphql-rust/0.10.0")
            .connection_verbose(true)
            //.danger_accept_invalid_certs(true)
            .build()?;

        let req_builder = client
            .post(conn.url())
            .headers(construct_headers())
            .basic_auth::<String, String>(conn.session_token.to_string(), None);

        Ok(req_builder)
    }

    pub fn schema(&self, req_builder: RequestBuilder) -> eyre::Result<IntrospectionResponse> {
        let request_body: graphql_client::QueryBody<()> = graphql_client::QueryBody {
            variables: (),
            query: introspection_query::QUERY,
            operation_name: introspection_query::OPERATION_NAME,
        };

        let res = req_builder.json(&request_body).send()?;

        if res.status().is_success() {
            // do nothing
        } else if res.status().is_server_error() {
            return Err(eyre::anyhow!("server error!"));
        } else {
            let status = res.status();
            let error_message = match res.text() {
                Ok(msg) => match serde_json::from_str::<serde_json::Value>(&msg) {
                    Ok(json) => {
                        format!("HTTP {}\n{}", status, serde_json::to_string_pretty(&json)?)
                    }
                    Err(_) => format!("HTTP {}: {}", status, msg),
                },
                Err(_) => format!("HTTP {}", status),
            };
            return Err(eyre::anyhow!(error_message));
        }

        let json: IntrospectionResponse = res.json()?;

        Ok(json)
    }
}

fn construct_headers() -> HeaderMap {
    let mut headers = HeaderMap::new();
    headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
    headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
    headers
}