pub use crate::common::VldBodyLimit;
use crate::common::{
DEFAULT_BODY_LIMIT, VldHttpError, cookie_headers_to_json, headers_to_json, parse_form_body,
parse_json_body, path_params_to_json, query_string_to_json, require_form_content_type,
require_json_content_type,
};
use poem::error::{ReadBodyError, ResponseError};
use poem::http::StatusCode;
use poem::{FromRequest, Request, RequestBody, Result};
use std::fmt;
use vld::schema::VldParse;
#[derive(Debug)]
pub struct VldPoemError {
inner: VldHttpError,
}
impl VldPoemError {
pub fn error(&self) -> &vld::error::VldError {
self.inner.error()
}
pub fn status(&self) -> StatusCode {
StatusCode::from_u16(self.inner.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
}
pub fn body(&self) -> serde_json::Value {
self.inner.body()
}
}
impl From<VldHttpError> for VldPoemError {
fn from(inner: VldHttpError) -> Self {
Self { inner }
}
}
impl From<vld::error::VldError> for VldPoemError {
fn from(e: vld::error::VldError) -> Self {
VldHttpError::from(e).into()
}
}
impl fmt::Display for VldPoemError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl std::error::Error for VldPoemError {}
impl ResponseError for VldPoemError {
fn status(&self) -> StatusCode {
VldPoemError::status(self)
}
fn as_response(&self) -> poem::Response {
poem::Response::builder()
.status(VldPoemError::status(self))
.content_type("application/json")
.body(self.body().to_string())
}
}
fn reject(e: VldHttpError) -> poem::Error {
VldPoemError::from(e).into()
}
fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T> {
crate::common::parse_coerced(value).map_err(|e| VldPoemError::from(e).into())
}
async fn read_limited_body(
req: &Request,
body: &mut RequestBody,
) -> Result<impl AsRef<[u8]> + use<>> {
let limit = req
.data::<VldBodyLimit>()
.map_or(DEFAULT_BODY_LIMIT, |l| l.0);
let body = body
.take()
.map_err(|e| reject(VldHttpError::parse(format!("Failed to read body: {e}"))))?;
body.into_bytes_limit(limit).await.map_err(|e| match e {
ReadBodyError::PayloadTooLarge => reject(VldHttpError::payload_too_large()),
other => reject(VldHttpError::parse(format!("Failed to read body: {other}"))),
})
}
#[derive(Debug, Clone)]
pub struct VldJson<T>(pub T);
impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldJson<T> {
async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> {
require_json_content_type(req.content_type()).map_err(reject)?;
let bytes = read_limited_body(req, body).await?;
T::vld_parse_value(&parse_json_body(bytes.as_ref()).map_err(reject)?)
.map(VldJson)
.map_err(|e| VldPoemError::from(e).into())
}
}
#[derive(Debug, Clone)]
pub struct VldQuery<T>(pub T);
impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldQuery<T> {
async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
validate(&query_string_to_json(req.uri().query().unwrap_or(""))).map(VldQuery)
}
}
#[derive(Debug, Clone)]
pub struct VldForm<T>(pub T);
impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldForm<T> {
async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> {
require_form_content_type(req.content_type()).map_err(reject)?;
let bytes = read_limited_body(req, body).await?;
validate(&parse_form_body(bytes.as_ref()).map_err(reject)?).map(VldForm)
}
}
#[derive(Debug, Clone)]
pub struct VldPath<T>(pub T);
impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldPath<T> {
async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
let params = req
.path_params::<std::collections::BTreeMap<String, String>>()
.unwrap_or_default();
validate(&path_params_to_json(
params.iter().map(|(k, v)| (k.as_str(), v.as_str())),
))
.map(VldPath)
}
}
#[derive(Debug, Clone)]
pub struct VldHeaders<T>(pub T);
impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldHeaders<T> {
async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
let value = headers_to_json(
req.headers()
.iter()
.map(|(n, v)| (n.as_str(), v.as_bytes())),
);
validate(&value).map(VldHeaders)
}
}
#[derive(Debug, Clone)]
pub struct VldCookie<T>(pub T);
impl<'a, T: VldParse + Send + Sync + 'static> FromRequest<'a> for VldCookie<T> {
async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
let value = cookie_headers_to_json(
req.headers()
.get_all(poem::http::header::COOKIE)
.iter()
.map(|v| v.as_bytes()),
);
validate(&value).map(VldCookie)
}
}
crate::impl_deref!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
pub mod prelude {
pub use super::{
VldBodyLimit, VldCookie, VldForm, VldHeaders, VldJson, VldPath, VldPoemError, VldQuery,
};
pub use vld::prelude::*;
}