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
use graphql_client::QueryBody;
use serde::Serialize;
use std::fmt::Debug;
use thiserror::Error;

#[derive(Clone)]
pub struct GraphQlClient {
    base_url: String,
    print_out: bool,
}

#[derive(Error, Debug)]
pub enum GraphQlClientError {
    #[error("request error")]
    ReqwestError(#[from] reqwest::Error),
}

impl GraphQlClient {
    pub fn new<S: Into<String>>(base_address: S) -> GraphQlClient {
        let base_url = format!("http://{}/graphql", base_address.into());
        GraphQlClient {
            base_url,
            print_out: true,
        }
    }

    pub fn base_url(&self) -> String {
        self.base_url.to_string()
    }

    pub fn enable_print(&mut self) {
        self.print_out = true;
    }

    pub fn disable_print(&mut self) {
        self.print_out = false;
    }

    pub fn run<T: Serialize>(
        &self,
        query: QueryBody<T>,
    ) -> Result<reqwest::blocking::Response, GraphQlClientError> {
        if self.print_out {
            println!(
                "running query: {:#?}, against: {}",
                query.operation_name, self.base_url
            );
        }
        reqwest::blocking::Client::new()
            .post(&self.base_url)
            .json(&query)
            .send()
            .map_err(|e| e.into())
    }
}