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
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
//! Use graphql_client inside browsers with [wasm-bindgen].
//!
//! This crate reexports all you need from graphql-client, so you do not need any other explicit dependencies.

#![deny(warnings)]
#![deny(missing_docs)]

use failure::*;
use futures::{Future, IntoFuture};
pub use graphql_client::{self, GraphQLQuery, Response};
use log::*;
use std::collections::HashMap;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;

/// The main interface to the library.
///
/// The workflow is the following:
///
/// - create a client
/// - (optionally) configure it
/// - use it to perform queries with the [call] method
pub struct Client {
    endpoint: String,
    headers: HashMap<String, String>,
}

/// All the ways a request can go wrong.
///
/// not exhaustive
#[derive(Debug, Fail, PartialEq)]
pub enum ClientError {
    /// The body couldn't be built
    #[fail(display = "Request body is not a valid string")]
    Body,
    /// An error caused by window.fetch
    #[fail(display = "Network error")]
    Network(String),
    /// Error in a dynamic JS cast that should have worked
    #[fail(display = "JS casting error")]
    Cast,
    /// No window object could be retrieved
    #[fail(
        display = "No Window object available - the client works only in a browser (non-worker) context"
    )]
    NoWindow,
    /// Response shape does not match the generated code
    #[fail(display = "Response shape error")]
    ResponseShape,
    /// Response could not be converted to text
    #[fail(display = "Response conversion to text failed (Response.text threw)")]
    ResponseText,
    /// Exception thrown when building the request
    #[fail(display = "Error building the request")]
    RequestError,
    /// Other JS exception
    #[fail(display = "Unexpected JS exception")]
    JsException,
}

impl Client {
    /// Initialize a client. The `endpoint` parameter is the URI of the GraphQL API.
    pub fn new<Endpoint>(endpoint: Endpoint) -> Client
    where
        Endpoint: Into<String>,
    {
        Client {
            endpoint: endpoint.into(),
            headers: HashMap::new(),
        }
    }

    /// Add a header to those sent with the requests. Can be used for things like authorization.
    pub fn add_header(&mut self, name: &str, value: &str) {
        self.headers.insert(name.into(), value.into());
    }

    /// Perform a query.
    ///
    // Lint disabled: We can pass by value because it's always an empty struct.
    #[allow(clippy::needless_pass_by_value)]
    pub fn call<Q: GraphQLQuery + 'static>(
        &self,
        _query: Q,
        variables: Q::Variables,
    ) -> impl Future<Item = graphql_client::Response<Q::ResponseData>, Error = ClientError> + 'static
    {
        // this can be removed when we convert to async/await
        let endpoint = self.endpoint.clone();
        let custom_headers = self.headers.clone();

        web_sys::window()
            .ok_or_else(|| ClientError::NoWindow)
            .into_future()
            .and_then(move |window| {
                serde_json::to_string(&Q::build_query(variables))
                    .map_err(|_| ClientError::Body)
                    .map(move |body| (window, body))
            })
            .and_then(move |(window, body)| {
                let mut request_init = web_sys::RequestInit::new();
                request_init
                    .method("POST")
                    .body(Some(&JsValue::from_str(&body)));

                web_sys::Request::new_with_str_and_init(&endpoint, &request_init)
                    .map_err(|_| ClientError::JsException)
                    .map(|request| (window, request))
                // "Request constructor threw");
            })
            .and_then(move |(window, request)| {
                let headers = request.headers();
                headers
                    .set("Content-Type", "application/json")
                    .map_err(|_| ClientError::RequestError)?;
                headers
                    .set("Accept", "application/json")
                    .map_err(|_| ClientError::RequestError)?;

                for (header_name, header_value) in custom_headers.iter() {
                    headers
                        .set(header_name, header_value)
                        .map_err(|_| ClientError::RequestError)?;
                }

                Ok((window, request))
            })
            .and_then(move |(window, request)| {
                JsFuture::from(window.fetch_with_request(&request))
                    .map_err(|err| ClientError::Network(js_sys::Error::from(err).message().into()))
            })
            .and_then(move |res| {
                debug!("response: {:?}", res);
                res.dyn_into::<web_sys::Response>()
                    .map_err(|_| ClientError::Cast)
            })
            .and_then(move |cast_response| {
                cast_response.text().map_err(|_| ClientError::ResponseText)
            })
            .and_then(move |text_promise| {
                JsFuture::from(text_promise).map_err(|_| ClientError::ResponseText)
            })
            .and_then(|text| {
                let response_text = text.as_string().unwrap_or_default();
                debug!("response text as string: {:?}", response_text);
                serde_json::from_str(&response_text).map_err(|_| ClientError::ResponseShape)
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn client_new() {
        Client::new("https://example.com/graphql");
        Client::new("/graphql");
    }
}