-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathasync_json_request.rs
46 lines (38 loc) · 1.28 KB
/
async_json_request.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#[cfg(not(feature = "serde"))]
fn main() {}
#[cfg(feature = "serde")]
#[tokio::main]
async fn main() {
use ::serde::de::DeserializeSeed;
use hebi::prelude::*;
let client = reqwest::Client::default();
async fn get(scope: Scope<'_>, client: reqwest::Client) -> hebi::Result<Value<'_>> {
let url = scope.param::<Str>(0)?;
let request = client.get(url.as_str());
let response = request.send().await.map_err(hebi::Error::user)?;
let bytes = response.bytes().await.map_err(hebi::Error::user)?.to_vec();
let str = String::from_utf8(bytes).map_err(hebi::Error::user)?;
let value = ValueDeserializer::new(scope.global())
.deserialize(&mut serde_json::de::Deserializer::from_str(&str))
.map_err(hebi::Error::user)?;
Ok(value)
}
let module = NativeModule::builder("http")
.async_function("get", move |scope| get(scope, client.clone()))
.finish();
let mut hebi = Hebi::new();
hebi.register(&module);
let result = hebi
.eval_async(
r#"
import http
response := http.get("https://jsonplaceholder.typicode.com/todos/1")
print "title: ", response["title"], " id: ", response["userId"]
response
"#,
)
.await
.unwrap();
println!("Result is:\n{result:?}");
println!("Serialized: {}", serde_json::to_string(&result).unwrap());
}