use serde::de::DeserializeOwned;
use serde::Deserialize;
#[derive(Debug, thiserror::Error)]
pub enum XrpcError {
#[error(transparent)]
Transport(#[from] reqwest::Error),
#[error("{status}{}{}", error.as_deref().map(|e| format!(" {e}")).unwrap_or_default(), message.as_deref().map(|m| format!(": {m}")).unwrap_or_default())]
Status {
status: reqwest::StatusCode,
error: Option<String>,
message: Option<String>,
body: String,
},
#[error("failed to decode response from {url}: {source}; body: {snippet}")]
Decode {
url: String,
snippet: String,
#[source]
source: serde_json::Error,
},
}
pub fn xrpc_url(base: &str, nsid: &str) -> String {
let base = base.trim_end_matches('/');
if base.starts_with("http://") || base.starts_with("https://") {
format!("{base}/xrpc/{nsid}")
} else {
format!("https://{base}/xrpc/{nsid}")
}
}
pub fn push_query<T: serde::Serialize>(
mut rb: reqwest::RequestBuilder,
params: &T,
) -> reqwest::RequestBuilder {
let value = match serde_json::to_value(params) {
Ok(serde_json::Value::Object(map)) => map,
_ => return rb,
};
for (key, value) in value {
match value {
serde_json::Value::Null => {}
serde_json::Value::Array(items) => {
for item in items {
rb = rb.query(&[(key.as_str(), scalar_to_string(&item))]);
}
}
other => {
rb = rb.query(&[(key.as_str(), scalar_to_string(&other))]);
}
}
}
rb
}
fn scalar_to_string(v: &serde_json::Value) -> String {
match v {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
}
}
pub async fn send<T: DeserializeOwned>(
rb: reqwest::RequestBuilder,
) -> Result<T, XrpcError> {
parse(rb.send().await?).await
}
pub async fn send_unit(rb: reqwest::RequestBuilder) -> Result<(), XrpcError> {
parse_unit(rb.send().await?).await
}
pub async fn send_bytes(
rb: reqwest::RequestBuilder,
) -> Result<Vec<u8>, XrpcError> {
parse_bytes(rb.send().await?).await
}
pub async fn parse<T: DeserializeOwned>(
res: reqwest::Response,
) -> Result<T, XrpcError> {
let (url, body) = success_body(res).await?;
serde_json::from_slice(&body).map_err(|source| XrpcError::Decode {
url,
snippet: snippet(&body),
source,
})
}
pub async fn parse_unit(res: reqwest::Response) -> Result<(), XrpcError> {
success_body(res).await.map(|_| ())
}
pub async fn parse_bytes(res: reqwest::Response) -> Result<Vec<u8>, XrpcError> {
success_body(res).await.map(|(_, body)| body.to_vec())
}
async fn success_body(
res: reqwest::Response,
) -> Result<(String, bytes::Bytes), XrpcError> {
let status = res.status();
let url = res.url().to_string();
let body = res.bytes().await?;
if status.is_success() {
return Ok((url, body));
}
#[derive(Deserialize)]
struct ErrorBody {
error: Option<String>,
message: Option<String>,
}
let parsed: Option<ErrorBody> = serde_json::from_slice(&body).ok();
Err(XrpcError::Status {
status,
error: parsed.as_ref().and_then(|e| e.error.clone()),
message: parsed.as_ref().and_then(|e| e.message.clone()),
body: String::from_utf8_lossy(&body).into_owned(),
})
}
fn snippet(body: &[u8]) -> String {
let s = String::from_utf8_lossy(body);
s.chars().take(300).collect()
}