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 +1,2 @@
log: func(level: string, message: string)
fetch: func(config: string) -> string

View File

@@ -29,6 +29,10 @@ impl container::Container for MyContainer {
println!("+ fetch: {}, time cost: {}ms", params, e.as_millis());
result
}
fn log(&mut self, level: &str, message: &str) {
println!("[{}] {}", level, message);
}
}
wit_bindgen_wasmtime::import!("../exports.wit");
@@ -45,13 +49,17 @@ fn main() -> Result<()> {
let eval_t1 = SystemTime::now();
let a = exports.eval_javascript(&mut store, r##"
function hi(name) { return "hi: " + name; }
console.log('hello', 1, true);
let a = [];
// a.push(console);
console.log('query: ' + 'print_request.action');
a.push(fetch('https://hatter.ink/util/print_request.action', {
headers: {
'Test-Header': 'this is a test header'
}
}));
// a.push(fetch('https://hatter.ink/ip.action'));
console.log('query: ' + 'ip.jsonp');
a.push(fetch('https://hatter.ink/ip/ip.jsonp'));
// a.push(fetch('https://hatter.ink/ip2.action'));
a.push({

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")));
}