src/tools.rs: new helper json_object_to_query

This commit is contained in:
Dietmar Maurer 2019-03-03 08:51:37 +01:00
parent 59b9c7ef5a
commit f5f13ebc5a
2 changed files with 36 additions and 6 deletions

View File

@ -17,7 +17,7 @@ use proxmox_backup::backup::*;
//use proxmox_backup::catar::encoder::*;
//use proxmox_backup::backup::datastore::*;
use serde_json::{Value};
use serde_json::{json, Value};
use hyper::Body;
use std::sync::Arc;
use regex::Regex;
@ -193,10 +193,10 @@ fn list_snapshots(
let path = tools::required_string_param(&param, "group")?;
let group = BackupGroup::parse(path)?;
let query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("backup-type", &group.backup_type)
.append_pair("backup-id", &group.backup_id)
.finish();
let query = tools::json_object_to_query(json!({
"backup-type": &group.backup_type,
"backup-id": &group.backup_id,
}))?;
let mut client = HttpClient::new(&repo.host, &repo.user);

View File

@ -17,7 +17,7 @@ use std::time::Duration;
use std::os::unix::io::RawFd;
use std::os::unix::io::AsRawFd;
use serde_json::Value;
use serde_json::{json, Value};
pub mod timer;
pub mod wrapped_reader_stream;
@ -320,6 +320,36 @@ pub fn nodename() -> &'static str {
&NODENAME
}
pub fn json_object_to_query(data: Value) -> Result<String, Error> {
let mut query = url::form_urlencoded::Serializer::new(String::new());
let object = data.as_object().ok_or_else(|| {
format_err!("json_object_to_query: got wrong data type (expected object).")
})?;
for (key, value) in object {
match value {
Value::Bool(b) => { query.append_pair(key, &b.to_string()); }
Value::Number(n) => { query.append_pair(key, &n.to_string()); }
Value::String(s) => { query.append_pair(key, &s); }
Value::Array(arr) => {
for element in arr {
match element {
Value::Bool(b) => { query.append_pair(key, &b.to_string()); }
Value::Number(n) => { query.append_pair(key, &n.to_string()); }
Value::String(s) => { query.append_pair(key, &s); }
_ => bail!("json_object_to_query: unable to handle complex array data types."),
}
}
}
_ => bail!("json_object_to_query: unable to handle complex data types."),
}
}
Ok(query.finish())
}
pub fn required_string_param<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> {
match param[name].as_str() {
Some(s) => Ok(s),