mirror of
https://github.com/tlsnotary/tlsn-js.git
synced 2026-01-08 20:18:01 -05:00
feat: Simplified fetch method (Rust wasm_bindgen)
This commit is contained in:
@@ -16,7 +16,7 @@ pub use wasm_bindgen_rayon::init_thread_pool;
|
||||
use js_sys::JSON;
|
||||
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
use web_sys::{Request as WebsysRequest, RequestInit, Response};
|
||||
use web_sys::{Request, RequestInit, Response};
|
||||
|
||||
// A macro to provide `println!(..)`-style syntax for `console.log` logging.
|
||||
macro_rules! log {
|
||||
@@ -28,17 +28,11 @@ pub(crate) use log;
|
||||
|
||||
extern crate console_error_panic_hook;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(js_namespace = self)]
|
||||
fn fetch(request: &web_sys::Request) -> js_sys::Promise;
|
||||
}
|
||||
|
||||
pub async fn fetch_as_json_string(url: &str, opts: &RequestInit) -> Result<String, JsValue> {
|
||||
let request = WebsysRequest::new_with_str_and_init(url, opts)?;
|
||||
let promise = fetch(&request);
|
||||
let future = JsFuture::from(promise);
|
||||
let resp_value = future.await?;
|
||||
let request = Request::new_with_str_and_init(url, opts)?;
|
||||
let window = web_sys::window().expect("Window object");
|
||||
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
|
||||
assert!(resp_value.is_instance_of::<Response>());
|
||||
let resp: Response = resp_value.dyn_into()?;
|
||||
let json = JsFuture::from(resp.json()?).await?;
|
||||
let stringified = JSON::stringify(&json)?;
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
extern crate wasm_bindgen_test;
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, str};
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen_test::*;
|
||||
use web_sys::RequestInit;
|
||||
|
||||
extern crate tlsn_extension_rs;
|
||||
use tlsn_extension_rs::*;
|
||||
@@ -18,6 +20,19 @@ macro_rules! log {
|
||||
|
||||
wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
async fn test_fetch() {
|
||||
let url = "https://swapi.info/api/";
|
||||
let mut opts = RequestInit::new();
|
||||
opts.method("GET");
|
||||
|
||||
let rust_string: String = tlsn_extension_rs::fetch_as_json_string(&url, &opts)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(rust_string.contains("starships"));
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
async fn verify() {
|
||||
let pem = str::from_utf8(include_bytes!("../../../test/assets/notary.pem")).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user