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
use poem::{Error, IntoResponse, Request, Response, Result};
use serde_json::Value;
use crate::{
payload::Payload,
poem::{FromRequest, RequestBody},
registry::{MetaSchemaRef, Registry},
types::Type,
ParseRequestError,
};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Json<T>(pub T);
#[poem::async_trait]
impl<T: Type> Payload for Json<T> {
const CONTENT_TYPE: &'static str = "application/json";
fn schema_ref() -> MetaSchemaRef {
T::schema_ref()
}
#[allow(unused_variables)]
fn register(registry: &mut Registry) {
T::register(registry)
}
async fn from_request(request: &Request, body: &mut RequestBody) -> Result<Self> {
let value = poem::web::Json::<Value>::from_request(request, body)
.await
.map_err(Error::bad_request)?;
let value = T::parse(value.0).map_err(|err| {
Error::bad_request(ParseRequestError::ParseRequestBody {
type_name: T::NAME,
reason: err.into_message(),
})
})?;
Ok(Self(value))
}
}
impl<T: Type> IntoResponse for Json<T> {
fn into_response(self) -> Response {
poem::web::Json(self.0.to_value()).into_response()
}
}