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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
mod binary;
mod json;
mod plain_text;
use std::io::{Cursor, ErrorKind};
pub use binary::Binary;
pub use json::Json;
pub use plain_text::PlainText;
use poem::{error::ReadBodyError, Body, IntoResponse, Request, RequestBody, Result};
use tokio::io::AsyncReadExt;
use crate::{
registry::{MetaSchemaRef, Registry},
ParseRequestError,
};
pub trait Payload: Send {
const CONTENT_TYPE: &'static str;
const IS_REQUIRED: bool = true;
fn schema_ref() -> MetaSchemaRef;
#[allow(unused_variables)]
fn register(registry: &mut Registry) {}
}
#[poem::async_trait]
pub trait ParsePayload: Sized {
async fn from_request(
request: &Request,
body: &mut RequestBody,
) -> Result<Self, ParseRequestError>;
}
#[poem::async_trait]
impl<T: ParsePayload> ParsePayload for Result<T> {
async fn from_request(
request: &Request,
body: &mut RequestBody,
) -> Result<Self, ParseRequestError> {
match T::from_request(request, body).await {
Ok(payload) => Ok(Ok(payload)),
Err(err) => Ok(Err(err.into())),
}
}
}
impl<T: Payload> Payload for Option<T> {
const CONTENT_TYPE: &'static str = T::CONTENT_TYPE;
const IS_REQUIRED: bool = false;
fn schema_ref() -> MetaSchemaRef {
T::schema_ref()
}
fn register(registry: &mut Registry) {
T::register(registry);
}
}
#[poem::async_trait]
impl<T: ParsePayload> ParsePayload for Option<T> {
async fn from_request(
request: &Request,
body: &mut RequestBody,
) -> Result<Self, ParseRequestError> {
let taked_body = body
.take()
.map_err(|err| ParseRequestError::ParseRequestBody(err.into_response()))?;
let mut body_reader = taked_body.into_async_read();
match body_reader.read_u8().await {
Ok(ch) => {
*body =
RequestBody::new(Body::from_async_read(Cursor::new([ch]).chain(body_reader)));
T::from_request(request, body).await.map(Some)
}
Err(err) => {
if err.kind() == ErrorKind::UnexpectedEof {
Ok(None)
} else {
Err(ParseRequestError::ParseRequestBody(
ReadBodyError::Io(err).into_response(),
))
}
}
}
}
}