2 use serde_json
::{json, Value}
;
4 use crate::api_schema
::router
::{HttpError, RpcEnvironment}
;
6 use hyper
::{Body, Response, StatusCode}
;
9 /// Extension to set error message for server side logging
10 pub struct ErrorMessageExtension(pub String
);
12 pub struct OutputFormatter
{
14 pub format_result
: fn(data
: Value
, rpcenv
: &RpcEnvironment
) -> Response
<Body
>,
16 pub format_error
: fn(err
: Error
) -> Response
<Body
>,
19 static JSON_CONTENT_TYPE
: &str = "application/json;charset=UTF-8";
22 fn json_response(result
: Value
) -> Response
<Body
> {
24 let json_str
= result
.to_string();
26 let raw
= json_str
.into_bytes();
28 let mut response
= Response
::new(raw
.into());
29 response
.headers_mut().insert(
31 header
::HeaderValue
::from_static(JSON_CONTENT_TYPE
));
36 fn json_format_result(data
: Value
, rpcenv
: &RpcEnvironment
) -> Response
<Body
> {
38 let mut result
= json
!({
42 if let Some(total
) = rpcenv
.get_result_attrib("total").and_then(|v
| v
.as_u64()) {
43 result
["total"] = Value
::from(total
);
46 if let Some(changes
) = rpcenv
.get_result_attrib("changes") {
47 result
["changes"] = changes
.clone();
53 fn json_format_error(err
: Error
) -> Response
<Body
> {
55 let mut response
= if let Some(apierr
) = err
.downcast_ref
::<HttpError
>() {
56 let mut resp
= Response
::new(Body
::from(apierr
.message
.clone()));
57 *resp
.status_mut() = apierr
.code
;
60 let mut resp
= Response
::new(Body
::from(err
.to_string()));
61 *resp
.status_mut() = StatusCode
::BAD_REQUEST
;
65 response
.headers_mut().insert(
67 header
::HeaderValue
::from_static(JSON_CONTENT_TYPE
));
69 response
.extensions_mut().insert(ErrorMessageExtension(err
.to_string()));
74 pub static JSON_FORMATTER
: OutputFormatter
= OutputFormatter
{
75 format_result
: json_format_result
,
76 format_error
: json_format_error
,
79 fn extjs_format_result(data
: Value
, rpcenv
: &RpcEnvironment
) -> Response
<Body
> {
81 let mut result
= json
!({
86 if let Some(total
) = rpcenv
.get_result_attrib("total").and_then(|v
| v
.as_u64()) {
87 result
["total"] = Value
::from(total
);
90 if let Some(changes
) = rpcenv
.get_result_attrib("changes") {
91 result
["changes"] = changes
.clone();
98 fn extjs_format_error(err
: Error
) -> Response
<Body
> {
100 let mut errors
= vec
![];
102 let message
= err
.to_string();
103 errors
.push(&message
);
111 let mut response
= json_response(result
);
113 response
.extensions_mut().insert(ErrorMessageExtension(message
));
118 pub static EXTJS_FORMATTER
: OutputFormatter
= OutputFormatter
{
119 format_result
: extjs_format_result
,
120 format_error
: extjs_format_error
,