proxmox-backup/src/server/formatter.rs

105 lines
2.4 KiB
Rust
Raw Normal View History

2018-12-05 11:42:25 +00:00
use failure::*;
use serde_json::{json, Value};
use crate::api::router::RpcEnvironment;
2018-12-05 17:22:56 +00:00
use hyper::{Body, Response, StatusCode};
use hyper::header;
2018-12-05 11:42:25 +00:00
pub struct OutputFormatter {
pub format_result: fn(data: Value, rpcenv: &RpcEnvironment) -> Response<Body>,
pub format_error: fn(err: Error) -> Response<Body>,
2018-12-05 11:42:25 +00:00
}
static JSON_CONTENT_TYPE: &str = "application/json;charset=UTF-8";
fn json_response(result: Value) -> Response<Body> {
let json_str = result.to_string();
let raw = json_str.into_bytes();
2018-12-05 11:42:25 +00:00
let mut response = Response::new(raw.into());
response.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(JSON_CONTENT_TYPE));
2018-12-05 11:42:25 +00:00
response
}
2018-12-05 17:22:56 +00:00
fn json_format_result(data: Value, rpcenv: &RpcEnvironment) -> Response<Body> {
2018-12-05 17:22:56 +00:00
let mut result = json!({
"data": data
});
2018-12-05 17:22:56 +00:00
if let Some(total) = rpcenv.get_result_attrib("total").and_then(|v| v.as_u64()) {
result["total"] = Value::from(total);
}
2018-12-05 17:22:56 +00:00
if let Some(changes) = rpcenv.get_result_attrib("changes") {
result["changes"] = changes.clone();
2018-12-05 17:22:56 +00:00
}
json_response(result)
}
fn json_format_error(err: Error) -> Response<Body> {
let mut response = Response::new(Body::from(err.to_string()));
response.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(JSON_CONTENT_TYPE));
*response.status_mut() = StatusCode::BAD_REQUEST;
response
2018-12-05 11:42:25 +00:00
}
pub static JSON_FORMATTER: OutputFormatter = OutputFormatter {
format_result: json_format_result,
format_error: json_format_error,
2018-12-05 11:42:25 +00:00
};
fn extjs_format_result(data: Value, rpcenv: &RpcEnvironment) -> Response<Body> {
2018-12-05 11:42:25 +00:00
let mut result = json!({
"data": data,
"success": true
});
2018-12-05 11:42:25 +00:00
if let Some(total) = rpcenv.get_result_attrib("total").and_then(|v| v.as_u64()) {
result["total"] = Value::from(total);
}
2018-12-05 17:22:56 +00:00
if let Some(changes) = rpcenv.get_result_attrib("changes") {
result["changes"] = changes.clone();
}
2018-12-05 17:22:56 +00:00
json_response(result)
}
2018-12-05 11:42:25 +00:00
fn extjs_format_error(err: Error) -> Response<Body> {
2018-12-05 11:42:25 +00:00
let mut errors = vec![];
let message = err.to_string();
errors.push(&message);
2018-12-05 11:42:25 +00:00
let result = json!({
"message": message,
"errors": errors,
"success": false
});
2018-12-05 11:42:25 +00:00
json_response(result)
2018-12-05 11:42:25 +00:00
}
pub static EXTJS_FORMATTER: OutputFormatter = OutputFormatter {
format_result: extjs_format_result,
format_error: extjs_format_error,
2018-12-05 11:42:25 +00:00
};