use serde::{Serialize, de::DeserializeOwned};
use crate::{Body, Error, Result};
pub(crate) enum Content {
Text(String),
Html(String),
Json(Vec<u8>),
Form(String),
}
impl Content {
pub(crate) fn text(text: impl Into<String>) -> Self {
Self::Text(text.into())
}
pub(crate) fn html(html: impl Into<String>) -> Self {
Self::Html(html.into())
}
pub(crate) fn json<T>(value: &T) -> Result<Self>
where
T: Serialize + ?Sized,
{
serde_json::to_vec(value)
.map(Self::Json)
.map_err(|_| Error::request("request JSON could not be encoded"))
}
pub(crate) fn form<T>(value: &T) -> Result<Self>
where
T: Serialize + ?Sized,
{
serde_urlencoded::to_string(value)
.map(Self::Form)
.map_err(|_| Error::request("request form could not be encoded"))
}
pub(crate) fn into_parts(self) -> (Body, &'static str) {
match self {
Self::Text(text) => (text.into(), "text/plain; charset=utf-8"),
Self::Html(html) => (html.into(), "text/html; charset=utf-8"),
Self::Json(json) => (json.into(), "application/json"),
Self::Form(form) => (form.into(), "application/x-www-form-urlencoded"),
}
}
}
pub(crate) fn decode_json<T>(bytes: &[u8], message: &'static str) -> Result<T>
where
T: DeserializeOwned,
{
serde_json::from_slice(bytes).map_err(|_| Error::decode(message))
}
pub(crate) fn decode_form<T>(bytes: &[u8], message: &'static str) -> Result<T>
where
T: DeserializeOwned,
{
serde_urlencoded::from_bytes(bytes).map_err(|_| Error::decode(message))
}