From b24b0be461ed39a96335e40561d07a35f2c3eb36 Mon Sep 17 00:00:00 2001 From: Christian Bourjau Date: Wed, 30 Oct 2019 21:32:31 +0100 Subject: [PATCH] wasm: Add bytes method to wasm response (#694) the bytes method was missing from the Response object of the wasm32 compilation target. --- Cargo.toml | 2 +- src/wasm/response.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 1a6da62..d288e8b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,10 +46,10 @@ __internal_proxy_sys_no_cache = [] [dependencies] http = "0.1.15" url = "2.1" +bytes = "0.4" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] base64 = "0.11" -bytes = "0.4" encoding_rs = "0.8" futures-core-preview = { version = "=0.3.0-alpha.19" } futures-util-preview = { version = "=0.3.0-alpha.19" } diff --git a/src/wasm/response.rs b/src/wasm/response.rs index cdf2600..93c97a2 100644 --- a/src/wasm/response.rs +++ b/src/wasm/response.rs @@ -1,5 +1,7 @@ use std::fmt; +use bytes::Bytes; +use js_sys::Uint8Array; use http::{HeaderMap, StatusCode}; /// A Response to a submitted `Request`. @@ -60,6 +62,22 @@ impl Response { Err(crate::error::decode("response.text isn't string")) } } + + /// Get the response as bytes + pub async fn bytes(self) -> crate::Result { + let p = self.http.body().array_buffer() + .map_err(crate::error::wasm) + .map_err(crate::error::decode)?; + + let buf_js = super::promise::(p) + .await + .map_err(crate::error::decode)?; + + let buffer = Uint8Array::new(&buf_js); + let mut bytes = vec![0; buffer.length() as usize]; + buffer.copy_to(&mut bytes); + Ok(bytes.into()) + } } impl fmt::Debug for Response {