feat: wit-bindgen-sample
This commit is contained in:
@@ -9,15 +9,12 @@ struct Exports;
|
||||
impl exports::Exports for Exports {
|
||||
fn eval_javascript(script: String) -> String {
|
||||
let mut ctx = Context::default();
|
||||
ctx.register_global_function("fetch", 0, fetch_fn);
|
||||
ctx.register_global_function("fetch", 0, do_fetch);
|
||||
let o = match ctx.eval(&script) {
|
||||
JsResult::Ok(o) => o,
|
||||
JsResult::Err(o) => o,
|
||||
};
|
||||
format!("{}", o.to_json(&mut ctx).unwrap())
|
||||
// let a = container::fetch("");
|
||||
// let a = fetch_from_host("<CONFIG>");
|
||||
// format!("eval: {}, fetched: {}", s, a)
|
||||
format!("{}", o.to_json(&mut ctx).expect("To JSON error"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,14 +24,17 @@ struct FetchResult {
|
||||
result: Option<String>,
|
||||
}
|
||||
|
||||
fn fetch_fn(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
|
||||
fn do_fetch(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
|
||||
if args.is_empty() {
|
||||
return JsResult::Err(JsValue::String(JsString::from("Requires at least one argument")));
|
||||
}
|
||||
let mut fetch_params_map = Map::new();
|
||||
fetch_params_map.insert("url".to_string(), args[0].to_json(ctx).expect("error"));
|
||||
if args.len() > 1 {
|
||||
fetch_params_map.insert("params".to_string(), args[1].to_json(ctx).expect("error"));
|
||||
}
|
||||
let fetch_params = format!("{}", Value::Object(fetch_params_map));
|
||||
|
||||
|
||||
let fetch_result_string = container::fetch(&fetch_params);
|
||||
let fetch_result: FetchResult = serde_json::from_str(&fetch_result_string).expect("from str error");
|
||||
if let Some(result) = fetch_result.result {
|
||||
@@ -42,5 +42,5 @@ fn fetch_fn(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValu
|
||||
let v = JsValue::from_json(&r, ctx).unwrap();
|
||||
return JsResult::Ok(v);
|
||||
}
|
||||
JsResult::Err(JsValue::String(JsString::from(format!("Invoke fetch error: {}", fetch_result.error.unwrap_or("".to_string())))))
|
||||
JsResult::Err(JsValue::String(JsString::from(format!("Invoke fetch error: {}", fetch_result.error.unwrap_or("<unknown>".to_string())))))
|
||||
}
|
||||
Reference in New Issue
Block a user