client.rs
2.9 KB
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
use js_sys::JsString;
use mogwai::prelude::*;
use wasm_bindgen::prelude::*;
use web_sys::{Window, window, Response, Request, RequestInit, RequestMode, Headers};
use super::error::*;
use std::result::Result as StdResult;
#[derive(Debug, Clone)]
pub(crate) struct Client {
window :Window,
}
type ReqGetter = fn(&str, &RequestInit) -> StdResult<Request, JsValue>;
const REQUEST :ReqGetter = Request::new_with_str_and_init;
impl Client {
pub fn new() -> Result<Self> {
const WINDOW_ERROR :&str = "Unable to get window instance";
Ok(Self { window: window()
. ok_or(Error::from(WINDOW_ERROR))? })
}
pub async fn get(&self, url :&str) -> Result<(Response, String)> {
let mut init = RequestInit::new();
let request = REQUEST( url
, init . method("GET")
. mode(RequestMode::Cors) )?;
request . headers()
. set("Accept", "application/json")?;
let response = JsFuture::from( self.window
. fetch_with_request(&request) )
. await?
. dyn_into::<Response>()?;
let data = JsFuture::from(response.text()?)
. await?
. dyn_into::<JsString>()?;
Ok((response, String::from(data)))
}
pub async fn put(&self, url :&str, data :&str) -> Result<Response> {
let mut init = RequestInit::new();
let request = REQUEST( url
, init . method("PUT")
. mode(RequestMode::Cors)
. body(Some(&data.into())) )?;
request . headers()
. set("Content-Type", "application/json")?;
let response = JsFuture::from( self.window
. fetch_with_request(&request))
. await?
. dyn_into::<Response>()?;
Ok(response)
}
pub async fn post_stream( &self
, url :&str
, mime_type :&str
, length :usize
, data :&JsValue ) -> Result<Response> {
let headers = Headers::new()?;
headers.set("Content-Type", mime_type)?;
headers.set("Content-Length", &format!("{}", length))?;
let mut init = RequestInit::new();
let request = REQUEST( url
, init . method("POST")
. mode(RequestMode::Cors)
. headers(&headers.into())
. body(Some(data)) )?;
let response = JsFuture::from( self.window
. fetch_with_request(&request))
. await?
. dyn_into::<Response>()?;
Ok(response)
}
}