use serde_json::{Map, Value};
pub(crate) fn tags_value(tags: Vec<String>) -> Value {
Value::Array(tags.into_iter().map(Value::String).collect())
}
pub(crate) fn insert_opt(map: &mut Map<String, Value>, key: &str, value: Option<Value>) {
if let Some(value) = value {
map.insert(key.to_string(), value);
}
}
pub(crate) fn insert_json_opt(
map: &mut Map<String, Value>,
key: &str,
raw: Option<String>,
) -> Result<(), i32> {
let Some(raw) = raw else { return Ok(()) };
match serde_json::from_str::<Value>(&raw) {
Ok(value) => {
map.insert(key.to_string(), value);
Ok(())
}
Err(err) => {
eprintln!("error: --{key} is not valid JSON: {err}");
Err(2)
}
}
}
pub(crate) fn to_body(map: Map<String, Value>) -> String {
Value::Object(map).to_string()
}
pub(crate) fn request(method: &str, path: &str, body: Option<&str>) -> i32 {
match crate::cli::http_request_json(method, path, body) {
Ok((status, resp)) if (200..300).contains(&status) => {
print_body(&resp);
0
}
Ok((status, resp)) => {
eprintln!("error: server returned HTTP {status}");
if !resp.is_empty() {
eprintln!("{resp}");
}
1
}
Err(_) => {
eprintln!("moadim is not running");
crate::cli::EXIT_NOT_RUNNING
}
}
}
pub(crate) fn print_body(body: &str) {
if body.is_empty() {
return;
}
match serde_json::from_str::<Value>(body) {
Ok(value) => println!(
"{}",
serde_json::to_string_pretty(&value).unwrap_or_default()
),
Err(_) => println!("{body}"),
}
}