feat: container

This commit is contained in:
2022-07-23 16:54:36 +08:00
parent b908736c1c
commit 842c5b4579
3 changed files with 33 additions and 1 deletions

View File

@@ -1,4 +1,6 @@
use boa_engine::{Context, JsResult, JsString, JsValue};
use boa_engine::object::ObjectInitializer;
use boa_engine::property::Attribute;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
@@ -11,21 +13,42 @@ impl exports::Exports for Exports {
fn eval_javascript(script: String) -> String {
let mut ctx = Context::default();
ctx.register_global_function("fetch", 0, do_fetch);
let console = ObjectInitializer::new(&mut ctx)
.function(console_info, "log", 0)
.build();
ctx.register_global_property("console", console, Attribute::empty());
let o = match ctx.eval(&script) {
JsResult::Ok(o) => o,
JsResult::Err(o) => o,
};
format!("{}", o.to_json(&mut ctx).expect("To JSON error"))
}
}
fn console_info(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let mut msg = String::new();
if args.len() == 0 {
msg.push_str("<empty>");
} else {
for (i, a) in args.iter().enumerate() {
if i > 0 { msg.push_str(", "); }
let a = a.to_string(ctx);
msg.push_str(&a.map(|s| s.to_string()).unwrap_or_else(|e| format!("<error: {:?}>", e)));
}
}
container::log("INFO", &msg);
Ok(JsValue::undefined())
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct FetchResult {
error: Option<String>,
result: Option<String>,
}
fn do_fetch(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
fn do_fetch(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
if args.is_empty() {
return JsResult::Err(JsValue::String(JsString::from("Requires at least one argument")));
}