proxmox-backup/src/server/formatter.rs

92 lines
2.3 KiB
Rust
Raw Normal View History

2018-12-05 11:42:25 +00:00
use failure::*;
use serde_json::{json, Value};
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 {
2018-12-05 17:22:56 +00:00
pub format_result: fn(data: Result<Value, Error>) -> Response<Body>,
2018-12-05 11:42:25 +00:00
}
2018-12-05 17:22:56 +00:00
fn json_format_result(data: Result<Value, Error>) -> Response<Body> {
2018-12-05 11:42:25 +00:00
let content_type = "application/json;charset=UTF-8";
2018-12-05 17:22:56 +00:00
match data {
Ok(value) => {
let result = json!({
"data": value
});
// todo: set result.total result.changes
let json_str = result.to_string();
let raw = json_str.into_bytes();
let mut response = Response::new(raw.into());
response.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(content_type));
return response;
}
Err(err) => {
let mut response = Response::new(Body::from(err.to_string()));
response.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(content_type));
*response.status_mut() = StatusCode::BAD_REQUEST;
return response;
}
}
2018-12-05 11:42:25 +00:00
}
pub static JSON_FORMATTER: OutputFormatter = OutputFormatter {
format_result: json_format_result,
};
2018-12-05 17:22:56 +00:00
fn extjs_format_result(data: Result<Value, Error>) -> Response<Body> {
2018-12-05 11:42:25 +00:00
let content_type = "application/json;charset=UTF-8";
2018-12-05 17:22:56 +00:00
let result = match data {
Ok(value) => {
let result = json!({
"data": value,
"success": true
});
// todo: set result.total result.changes
result
}
Err(err) => {
let mut errors = vec![];
errors.push(err.to_string());
let result = json!({
"errors": errors,
"success": false
});
2018-12-05 11:42:25 +00:00
2018-12-05 17:22:56 +00:00
result
}
};
2018-12-05 11:42:25 +00:00
let json_str = result.to_string();
let raw = json_str.into_bytes();
2018-12-05 17:22:56 +00:00
let mut response = Response::new(raw.into());
response.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(content_type));
response
2018-12-05 11:42:25 +00:00
}
pub static EXTJS_FORMATTER: OutputFormatter = OutputFormatter {
format_result: extjs_format_result,
};