canapi_stdweb/
lib.rs

1extern crate canapi;
2extern crate serde_json;
3extern crate serde_qs;
4extern crate stdweb;
5
6use canapi::{Endpoint, Error, Fetch};
7use serde_qs as qs;
8use stdweb::web::{XmlHttpRequest, XhrReadyState};
9
10pub struct WebFetch;
11
12impl Fetch for WebFetch {
13    fn fetch<T: Endpoint>(method: &'static str, url: String, query: Option<T>) -> Result<T, Error> {
14        let req = XmlHttpRequest::new();
15        let url = if method == "GET" {
16            if let Some(q) = query {
17                let query = qs::to_string(&q);
18                if let Err(_) = query {
19                    return Err(Error::SerDe(String::from("Query serialization error")))
20                }
21
22                format!("{}?{}", url, query.unwrap())
23            } else {
24                url
25            }
26        } else {
27            url
28        };
29        req.open(method, url.as_ref()).expect("XHR.open error");
30        req.send().expect("XHR.send error");
31        while req.ready_state() == XhrReadyState::Loading {}
32        if req.ready_state() == XhrReadyState::Done {
33            let res = req.response_text().expect("Network error when fetching API endpoint")
34                .expect("Response body is empty");
35            serde_json::from_str(res.as_ref()).map_err(|_| Error::SerDe(String::from("Error in the response")))
36        } else {
37            Err(Error::Fetch(String::from("Request didn't ended correctly")))
38        }
39    }
40}