use std::fmt::Debug;
use std::io;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use crate::net::Response;
use crate::prelude::*;
use crate::utils::{self, ResultExt};
#[derive(Debug)]
pub struct Request {
method: String,
headers: web_sys::Headers,
url: String,
}
impl Request {
pub fn new(method: &str, url: &str) -> Self {
Self {
method: method.to_owned(),
url: url.to_owned(),
headers: web_sys::Headers::new().unwrap_throw(),
}
}
pub fn connect(url: &str) -> Self {
Self::new("CONNECT", url)
}
pub fn delete(url: &str) -> Self {
Self::new("DELETE", url)
}
pub fn get(url: &str) -> Self {
Self::new("GET", url)
}
pub fn head(url: &str) -> Self {
Self::new("HEAD", url)
}
pub fn options(url: &str) -> Self {
Self::new("OPTIONS", url)
}
pub fn patch(url: &str) -> Self {
Self::new("PATCH", url)
}
pub fn post(url: &str) -> Self {
Self::new("POST", url)
}
pub fn put(url: &str) -> Self {
Self::new("PUT", url)
}
pub fn trace(url: &str) -> Self {
Self::new("TRACE", url)
}
pub fn header(&self, name: &str) -> Option<String> {
self.headers.get(name).unwrap_throw()
}
pub fn insert_header(&self, name: &str, val: &str) {
self.headers.append(name, val).unwrap_throw();
}
pub fn contains_header(&self, name: &str) -> bool {
self.headers.has(name).unwrap_throw()
}
pub fn remove_header(&self, name: &str) {
self.headers.delete(name).unwrap_throw();
}
pub async fn send(self) -> Result<Response, io::Error> {
let mut init = web_sys::RequestInit::new();
init.method(&self.method);
init.headers(self.headers.as_ref());
let req = web_sys::Request::new_with_str_and_init(&self.url, &init).unwrap_throw();
let fut = JsFuture::from(utils::window().fetch_with_request(&req));
let res = fut.await.err_kind(io::ErrorKind::Other)?;
debug_assert!(res.is_instance_of::<web_sys::Response>());
Ok(Response::new(res.dyn_into().unwrap_throw()))
}
}