use serde::Serialize;
use serde_json::{Map, Value};
use crate::error::{Error, Result};
pub(crate) fn to_value(params: impl Serialize) -> Result<Value> {
serde_json::to_value(params).map_err(|error| {
Error::client(
format!("could not serialize the request parameters: {error}"),
"invalid_params",
)
.with_source(error)
})
}
pub(crate) fn to_body(params: impl Serialize) -> Result<Option<Vec<u8>>> {
let value = to_value(params)?;
body_from_value(&value)
}
pub(crate) fn body_from_value(value: &Value) -> Result<Option<Vec<u8>>> {
if value.is_null() {
return Ok(None);
}
serde_json::to_vec(value).map(Some).map_err(|error| {
Error::client(
format!("could not serialize the request body: {error}"),
"invalid_params",
)
.with_source(error)
})
}
pub(crate) fn body_or_none(value: &Value) -> Result<Option<Vec<u8>>> {
match value {
Value::Object(map) if map.is_empty() => Ok(None),
other => body_from_value(other),
}
}
pub(crate) fn query(params: impl Serialize) -> Result<String> {
Ok(query_of_value(&to_value(params)?))
}
pub(crate) fn query_of_value(value: &Value) -> String {
let Some(map) = value.as_object() else {
return String::new();
};
let mut out = String::new();
for (key, value) in map {
if value.is_null() {
continue;
}
out.push(if out.is_empty() { '?' } else { '&' });
out.push_str(&encode(key));
out.push('=');
out.push_str(&encode(&scalar(value)));
}
out
}
pub(crate) fn query_pick(value: &Value, keys: &[&str]) -> String {
let mut picked = Map::new();
if let Some(map) = value.as_object() {
for key in keys {
if let Some(found) = map.get(*key) {
picked.insert((*key).to_string(), found.clone());
}
}
}
query_of_value(&Value::Object(picked))
}
pub(crate) fn take(value: &mut Value, key: &str) -> Value {
value
.as_object_mut()
.and_then(|map| map.remove(key))
.unwrap_or(Value::Null)
}
fn scalar(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Bool(flag) => flag.to_string(),
Value::Number(number) => number.to_string(),
Value::Array(items) => items.iter().map(scalar).collect::<Vec<_>>().join(","),
other => other.to_string(),
}
}
pub(crate) fn encode(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.as_bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
out.push(*byte as char)
}
other => out.push_str(&format!("%{other:02X}")),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn nulls_are_dropped_from_the_query() {
let rendered = query(json!({ "limit": 10, "cursor": null })).unwrap();
assert_eq!(rendered, "?limit=10");
}
#[test]
fn no_params_is_no_query() {
assert_eq!(query(()).unwrap(), "");
assert_eq!(query(json!({})).unwrap(), "");
}
#[test]
fn arrays_are_comma_joined() {
let rendered = query(json!({ "status": ["queued", "sent"] })).unwrap();
assert_eq!(rendered, "?status=queued%2Csent");
}
#[test]
fn a_path_segment_cannot_escape_itself() {
assert_eq!(encode("../domains"), "..%2Fdomains");
assert_eq!(encode("txemail_abc123"), "txemail_abc123");
}
}