use crate::Error;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct HttpRequest {
pub method: Method,
pub url: String,
pub headers: Vec<Header>,
#[cfg_attr(
feature = "unstable-wasm",
serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes"),
tsify(type = "Uint8Array")
)]
pub body: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "UPPERCASE")
)]
pub enum Method {
Get,
Post,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct HttpResponse {
pub status: u16,
pub headers: Vec<Header>,
#[cfg_attr(
feature = "unstable-wasm",
serde(with = "serde_bytes"),
tsify(type = "Uint8Array")
)]
pub body: Vec<u8>,
}
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
#[cfg_attr(feature = "uniffi", uniffi::export(Debug, Display))]
#[cfg_attr(
feature = "unstable-wasm",
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct Header {
pub name: String,
pub value: String,
}
impl std::fmt::Debug for Header {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Header")
.field("name", &self.name)
.finish_non_exhaustive()
}
}
impl std::fmt::Display for Header {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self, formatter)
}
}
impl HttpRequest {
pub(crate) fn get<'a>(
endpoint: &str,
path: &str,
parameters: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Self {
let query = form_urlencoded::Serializer::new(String::new())
.extend_pairs(parameters)
.finish();
Self {
method: Method::Get,
url: format!("{}/{path}?{query}", endpoint.trim_end_matches('/')),
headers: Vec::new(),
body: None,
}
}
}
impl HttpResponse {
pub(crate) fn success_body(&self) -> Result<&[u8], Error> {
match self.status {
200..=299 => Ok(&self.body),
301 | 302 | 303 | 307 | 308 => Err(Error::Moved {
location: self.header("location").map(str::to_owned),
}),
401 => Err(Error::Unauthorized),
403 => Err(Error::Blocked),
429 => Err(Error::RateLimited),
500..=599 => Err(Error::Unavailable),
status => Err(Error::Server {
status,
message: String::from_utf8_lossy(&self.body)
.chars()
.take(200)
.collect(),
}),
}
}
pub(crate) fn json<'a, T: serde::Deserialize<'a>>(&'a self) -> Result<T, Error> {
serde_json::from_slice(self.success_body()?).map_err(|error| Error::Parse {
message: error.to_string(),
})
}
fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|header| header.name.eq_ignore_ascii_case(name))
.map(|header| header.value.as_str())
}
}