]> git.proxmox.com Git - proxmox-backup.git/blob - src/server/formatter.rs
simplify formatter code
[proxmox-backup.git] / src / server / formatter.rs
1 use failure::*;
2 use serde_json::{json, Value};
3
4 use hyper::{Body, Response, StatusCode};
5 use hyper::header;
6
7 pub struct OutputFormatter {
8
9 pub format_result: fn(data: Result<Value, Error>) -> Response<Body>,
10 }
11
12 fn json_format_result(data: Result<Value, Error>) -> Response<Body> {
13
14 let content_type = "application/json;charset=UTF-8";
15
16 match data {
17 Ok(value) => {
18 let result = json!({
19 "data": value
20 });
21
22 // todo: set result.total result.changes
23
24 let json_str = result.to_string();
25
26 let raw = json_str.into_bytes();
27
28 let mut response = Response::new(raw.into());
29 response.headers_mut().insert(
30 header::CONTENT_TYPE,
31 header::HeaderValue::from_static(content_type));
32 return response;
33 }
34 Err(err) => {
35 let mut response = Response::new(Body::from(err.to_string()));
36 response.headers_mut().insert(
37 header::CONTENT_TYPE,
38 header::HeaderValue::from_static(content_type));
39 *response.status_mut() = StatusCode::BAD_REQUEST;
40 return response;
41 }
42 }
43 }
44
45 pub static JSON_FORMATTER: OutputFormatter = OutputFormatter {
46 format_result: json_format_result,
47 };
48
49 fn extjs_format_result(data: Result<Value, Error>) -> Response<Body> {
50
51 let content_type = "application/json;charset=UTF-8";
52
53 let result = match data {
54 Ok(value) => {
55 let result = json!({
56 "data": value,
57 "success": true
58 });
59
60 // todo: set result.total result.changes
61
62 result
63 }
64 Err(err) => {
65 let mut errors = vec![];
66
67 errors.push(err.to_string());
68
69 let result = json!({
70 "errors": errors,
71 "success": false
72 });
73
74 result
75 }
76 };
77
78 let json_str = result.to_string();
79
80 let raw = json_str.into_bytes();
81
82 let mut response = Response::new(raw.into());
83 response.headers_mut().insert(
84 header::CONTENT_TYPE,
85 header::HeaderValue::from_static(content_type));
86 response
87 }
88
89 pub static EXTJS_FORMATTER: OutputFormatter = OutputFormatter {
90 format_result: extjs_format_result,
91 };