1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use crate::api::{ ApiBody, ApiBodyInfo, ApiError };
use async_trait::async_trait;
use serde::Serialize;
type HttpResponse = http::Response<Vec<u8>>;
#[async_trait]
pub trait HandlerResponse {
type ResponseBody: ApiBody;
async fn handler_response(self) -> Result<HttpResponse, ApiError>;
}
pub struct ToJson<T: ApiBody>(pub T);
#[async_trait]
impl <T: ApiBody + Serialize + Send> HandlerResponse for ToJson<T> {
type ResponseBody = T;
async fn handler_response(self) -> Result<HttpResponse, ApiError> {
let body = serde_json::to_vec(&self.0).unwrap();
let res = http::Response::builder()
.header("content-type", "application/json")
.body(body)
.unwrap();
Ok(res)
}
}
impl <T> ApiBody for ToJson<T> where T: ApiBody {
fn api_body_info() -> ApiBodyInfo {
T::api_body_info()
}
}
#[async_trait]
impl <T> HandlerResponse for Option<T>
where
T: HandlerResponse + Send
{
type ResponseBody = <T as HandlerResponse>::ResponseBody;
async fn handler_response(self) -> Result<HttpResponse, ApiError> {
let res = self.ok_or_else(|| ApiError::path_not_found())?;
res.handler_response().await.map_err(|e| e.into())
}
}
#[async_trait]
impl <T, E> HandlerResponse for Result<T,E>
where
T: HandlerResponse + Send,
E: Into<ApiError> + Send + 'static,
{
type ResponseBody = <T as HandlerResponse>::ResponseBody;
async fn handler_response(self) -> Result<HttpResponse, ApiError> {
let res = self.map_err(|e| e.into())?;
res.handler_response().await.map_err(|e| e.into())
}
}