use crate::utils::*;
use crate::{any::Any, array::ArrayBuffer, error::*, promise::Promise, string::JsString};
#[derive(Clone, Debug, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct Response {
inner: emlite::Val,
}
bind!(Response);
impl_dyn_cast!(Response);
impl Response {
pub fn ok(&self) -> bool {
self.inner.get("ok").as_::<bool>()
}
pub fn status(&self) -> u16 {
self.inner.get("status").as_::<u32>() as u16
}
pub fn headers_raw(&self) -> Any {
self.inner.get("headers")
}
pub fn text(&self) -> Promise<Result<JsString, JsError>> {
self.inner.call("text", &[]).as_::<Promise<_>>()
}
pub fn json(&self) -> Promise<Result<Any, JsError>> {
self.inner.call("json", &[]).as_::<Promise<_>>()
}
pub fn array_buffer(&self) -> Promise<Result<ArrayBuffer, JsError>> {
self.inner.call("arrayBuffer", &[]).as_::<Promise<_>>()
}
}
pub fn fetch(input: &str, init: Option<&Any>) -> Promise<Result<Response, JsError>> {
let fetch_fn = emlite::Val::global("fetch");
if !fetch_fn.is_function() {
let err = JsError::new("globalThis.fetch is not available");
return Promise::reject(err);
}
let mut args: alloc::vec::Vec<emlite::Val> = alloc::vec::Vec::with_capacity(2);
args.push(input.into());
if let Some(i) = init {
args.push(i.clone());
}
fetch_fn.invoke(&args).as_::<Promise<_>>()
}
pub fn fetch_val(input: &Any, init: Option<&Any>) -> Promise<Result<Response, JsError>> {
let fetch_fn = emlite::Val::global("fetch");
if !fetch_fn.is_function() {
let err = JsError::new("globalThis.fetch is not available");
return Promise::reject(err);
}
let mut args: alloc::vec::Vec<emlite::Val> = alloc::vec::Vec::with_capacity(2);
args.push(input.clone());
if let Some(i) = init {
args.push(i.clone());
}
fetch_fn.invoke(&args).as_::<Promise<_>>()
}