Add multipart for WASM (#966)

This commit is contained in:
Enno Boland
2020-07-08 22:10:23 +02:00
committed by GitHub
parent af9fc5c9d8
commit a800202384
7 changed files with 335 additions and 13 deletions

View File

@@ -1,6 +1,9 @@
use super::multipart::Form;
/// dox
use bytes::Bytes;
use std::fmt;
use js_sys::Uint8Array;
use wasm_bindgen::JsValue;
/// The body of a `Request`.
///
@@ -9,39 +12,73 @@ use std::fmt;
/// passing many things (like a string or vector of bytes).
///
/// [builder]: ./struct.RequestBuilder.html#method.body
pub struct Body(Bytes);
pub struct Body {
inner: Inner,
}
enum Inner {
Bytes(Bytes),
Multipart(Form),
}
impl Body {
pub(crate) fn bytes(&self) -> &Bytes {
&self.0
pub(crate) fn to_js_value(&self) -> crate::Result<JsValue> {
match &self.inner {
Inner::Bytes(body_bytes) => {
let body_bytes: &[u8] = body_bytes.as_ref();
let body_array: Uint8Array = body_bytes.into();
let js_value: &JsValue = body_array.as_ref();
Ok(js_value.to_owned())
}
Inner::Multipart(form) => {
let form_data = form.to_form_data()?;
let js_value: &JsValue = form_data.as_ref();
Ok(js_value.to_owned())
}
}
}
#[inline]
pub(crate) fn from_form(f: Form) -> Body {
Self {
inner: Inner::Multipart(f),
}
}
}
impl From<Bytes> for Body {
#[inline]
fn from(bytes: Bytes) -> Body {
Body(bytes)
Body {
inner: Inner::Bytes(bytes),
}
}
}
impl From<Vec<u8>> for Body {
#[inline]
fn from(vec: Vec<u8>) -> Body {
Body(vec.into())
Body {
inner: Inner::Bytes(vec.into()),
}
}
}
impl From<&'static [u8]> for Body {
#[inline]
fn from(s: &'static [u8]) -> Body {
Body(Bytes::from_static(s))
Body {
inner: Inner::Bytes(Bytes::from_static(s)),
}
}
}
impl From<String> for Body {
#[inline]
fn from(s: String) -> Body {
Body(s.into())
Body {
inner: Inner::Bytes(s.into()),
}
}
}