Skip to content

Commit

Permalink
wasm: don't send request body as plain uint8 array (#1358)
Browse files Browse the repository at this point in the history
Co-authored-by: Niklas Wolber <niklas.wolber+git@octopost.eu>
  • Loading branch information
nwolber and nwolber committed Oct 17, 2021
1 parent fead177 commit bb3d102
Showing 1 changed file with 15 additions and 19 deletions.
34 changes: 15 additions & 19 deletions src/wasm/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use super::multipart::Form;
/// dox
use bytes::Bytes;
use js_sys::{Array, Uint8Array};
use js_sys::{Uint8Array};
use std::fmt;
use wasm_bindgen::JsValue;

Expand Down Expand Up @@ -40,8 +40,7 @@ impl Body {
Inner::Bytes(body_bytes) => {
let body_bytes: &[u8] = body_bytes.as_ref();
let body_uint8_array: Uint8Array = body_bytes.into();
let body_array = Array::from(&body_uint8_array);
let js_value: &JsValue = body_array.as_ref();
let js_value: &JsValue = body_uint8_array.as_ref();
Ok(js_value.to_owned())
}
#[cfg(feature = "multipart")]
Expand Down Expand Up @@ -131,8 +130,8 @@ impl fmt::Debug for Body {

#[cfg(test)]
mod tests {
use js_sys::{Array, Uint8Array};
use wasm_bindgen::{prelude::*, JsValue};
// use js_sys::{Array, Uint8Array};
use wasm_bindgen::{prelude::*};
use wasm_bindgen_test::*;

wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
Expand All @@ -157,20 +156,17 @@ mod tests {
async fn test_body_js() {
use crate::Body;

let body = Body::from("TEST");
let body_value = "TEST";
let body = Body::from(body_value);

let mut init = web_sys::RequestInit::new();
init.method("POST");
init.body(Some(body.to_js_value().expect("could not convert body to JsValue").as_ref()));

let js_req = web_sys::Request::new_with_str_and_init("", &init).expect("could not create JS request");
let text_promise = js_req.text().expect("could not get text promise");
let text = crate::wasm::promise::<JsValue>(text_promise).await.expect("could not get request body as text");

let arr = [84u8, 69, 83, 84];
let u8_arr: Uint8Array = arr.as_ref().into();
let expected = JsValue::from(Array::from(&u8_arr));

// ty JS -.-
assert_eq!(
format!("{:#?}", expected),
format!(
"{:#?}",
body.to_js_value()
.expect("could not convert body to JsValue")
)
);
assert_eq!(text.as_string().expect("text is not a string"), body_value);
}
}

0 comments on commit bb3d102

Please sign in to comment.