feat: fetch

This commit is contained in:
2022-07-17 10:37:34 +08:00
parent 74a202f1ed
commit 6890520435
3 changed files with 59 additions and 5 deletions

View File

@@ -1,19 +1,37 @@
use anyhow::Result;
use serde::{Deserialize, Serialize};
use wasmtime::{Config, Engine, Instance, Linker, Module, Store};
use container::*;
wit_bindgen_wasmtime::export!("../container.wit");
#[derive(Clone, Debug, Serialize, Deserialize)]
struct FetchResult {
error: Option<String>,
result: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct JsResult {
message: String,
}
#[derive(Default)]
pub struct MyContainer;
impl Container for MyContainer {
fn fetch(&mut self, s: &str) -> String {
// format!("FETCHED: {}", s)
let r = "{\"result\":\"{}\"}".into();
println!(">>>> {}", r);
r
// // format!("FETCHED: {}", s)
// let r = "{\"result\":\"{}\"}".into();
// println!(">>>> {}", r);
// r
serde_json::to_string(&FetchResult {
error: None,
result: Some(serde_json::to_string(&JsResult {
message: format!("inputs: {}", s),
}).expect("to json failed.1")),
}).expect("to json failed.2")
}
}
@@ -28,7 +46,16 @@ fn main() -> Result<()> {
|linker| container::add_to_linker(linker, |cx| -> &mut MyContainer { &mut cx.imports }),
|store, module, linker| Exports::instantiate(store, module, linker, |cx| &mut cx.exports),
)?;
let a = exports.eval_javascript(&mut store, "let a = [];fetch('aaa')");
let a = exports.eval_javascript(&mut store, r##"
let a = [];
a.push(fetch('https://www.google.com/'));
for (let i = 0; i < 3; i++) { a.push(i); }
a.push({
id: 1, name: 'hatter'
});
//JSON.stringify(a)
a
"##);
match a {
Ok(a) => println!("Hello, world! {:?}", a),