return response object

This commit is contained in:
Toshit Chawda 2024-01-10 22:47:41 -08:00
parent 3b4cd96614
commit eb511a317d
No known key found for this signature in database
GPG key ID: 91480ED99E2B3D9D
6 changed files with 167 additions and 72 deletions

View file

@ -17,50 +17,51 @@ extern "C" {
pub fn console_error(s: &str);
}
#[allow(unused_macros)]
macro_rules! debug {
($($t:tt)*) => (utils::console_debug(&format_args!($($t)*).to_string()))
}
#[allow(unused_macros)]
macro_rules! log {
($($t:tt)*) => (utils::console_log(&format_args!($($t)*).to_string()))
}
#[allow(unused_macros)]
macro_rules! error {
($($t:tt)*) => (utils::console_error(&format_args!($($t)*).to_string()))
}
macro_rules! nerr {
($expr:expr) => (JsError::new($expr))
#[allow(unused_macros)]
macro_rules! jerr {
($expr:expr) => {
JsError::new($expr)
};
}
pub fn entries_of_object(obj: &Object) -> Vec<Vec<String>> {
js_sys::Object::entries(obj)
.to_vec()
.iter()
.map(|val| {
Array::from(val)
.to_vec()
.iter()
.map(|val| {
val.as_string()
.expect_throw("failed to get string from object entry")
})
.collect()
})
.collect::<Vec<Vec<_>>>()
#[allow(unused_macros)]
macro_rules! jval {
($expr:expr) => {
JsValue::from($expr)
};
}
pub trait ReplaceErr {
type Ok;
fn replace_err(self, err: &str) -> Result<Self::Ok, JsError>;
fn replace_err_jv(self, err: &str) -> Result<Self::Ok, JsValue>;
}
impl<T, E> ReplaceErr for Result<T, E> {
type Ok = T;
fn replace_err(self, err: &str) -> Result<<Self as ReplaceErr>::Ok, JsError> {
self.map_err(|_| JsError::new(err))
self.map_err(|_| jerr!(err))
}
fn replace_err_jv(self, err: &str) -> Result<<Self as ReplaceErr>::Ok, JsValue> {
self.map_err(|_| jval!(err))
}
}
@ -68,6 +69,33 @@ impl<T> ReplaceErr for Option<T> {
type Ok = T;
fn replace_err(self, err: &str) -> Result<<Self as ReplaceErr>::Ok, JsError> {
self.ok_or_else(|| JsError::new(err))
self.ok_or_else(|| jerr!(err))
}
fn replace_err_jv(self, err: &str) -> Result<<Self as ReplaceErr>::Ok, JsValue> {
self.ok_or_else(|| jval!(err))
}
}
pub fn entries_of_object(obj: &Object) -> Vec<Vec<String>> {
js_sys::Object::entries(obj)
.to_vec()
.iter()
.filter_map(|val| {
Array::from(val)
.to_vec()
.iter()
.map(|val| val.as_string())
.collect::<Option<Vec<_>>>()
})
.collect::<Vec<Vec<_>>>()
}
pub fn define_property_obj(value: JsValue, writable: bool) -> Result<Object, JsValue> {
let entries: Array = vec![
Array::of2(&jval!("value"), &jval!(value)),
Array::of2(&jval!("writable"), &jval!(writable)),
]
.iter().collect::<Array>();
Object::from_entries(&entries)
}