use super::ntex;
pub use crate::common::VldBodyLimit;
use crate::common::{
DEFAULT_BODY_LIMIT, VldHttpError, cookie_headers_to_json, headers_to_json, parse_coerced,
parse_form_body, parse_json_body, path_params_to_json, query_string_to_json,
require_form_content_type, require_json_content_type,
};
use ntex::http::{Payload, StatusCode, header};
use ntex::web::{HttpRequest, HttpResponse, HttpResponseBuilder};
use std::fmt;
use vld::schema::VldParse;
#[derive(Debug)]
pub struct VldNtexError(VldHttpError);
impl VldNtexError {
pub fn error(&self) -> &vld::error::VldError {
self.0.error()
}
pub fn status(&self) -> StatusCode {
StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
}
pub fn body(&self) -> serde_json::Value {
self.0.body()
}
}
impl From<VldHttpError> for VldNtexError {
fn from(e: VldHttpError) -> Self {
Self(e)
}
}
impl From<vld::error::VldError> for VldNtexError {
fn from(e: vld::error::VldError) -> Self {
Self(e.into())
}
}
impl fmt::Display for VldNtexError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for VldNtexError {}
impl VldNtexError {
pub(super) fn render(&self) -> HttpResponse {
HttpResponseBuilder::new(self.status())
.header("content-type", "application/json")
.body(self.0.body().to_string())
}
}
async fn read_body(req: &HttpRequest, payload: &mut Payload) -> Result<Vec<u8>, VldHttpError> {
let limit = super::compat::app_value::<VldBodyLimit>(req).map_or(DEFAULT_BODY_LIMIT, |l| l.0);
#[cfg(feature = "ntex-compress")]
let mut stream = ntex::http::encoding::Decoder::from_headers(payload.take(), req.headers());
#[cfg(not(feature = "ntex-compress"))]
let mut stream = payload.take();
let mut body = Vec::new();
while let Some(chunk) = ntex::util::stream_recv(&mut stream).await {
let chunk =
chunk.map_err(|e| VldHttpError::parse(format!("Failed to read request body: {e}")))?;
if body.len() + chunk.len() > limit {
return Err(VldHttpError::payload_too_large());
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
fn content_type(req: &HttpRequest) -> Option<&str> {
req.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
}
fn validate<T: VldParse>(value: &serde_json::Value) -> Result<T, VldNtexError> {
parse_coerced(value).map_err(VldNtexError::from)
}
pub struct VldJson<T>(pub T);
impl<T: VldParse> VldJson<T> {
pub(super) async fn extract(
req: &HttpRequest,
payload: &mut Payload,
) -> Result<Self, VldNtexError> {
require_json_content_type(content_type(req))?;
let body = read_body(req, payload).await?;
T::vld_parse_value(&parse_json_body(&body)?)
.map(VldJson)
.map_err(VldNtexError::from)
}
}
pub struct VldQuery<T>(pub T);
impl<T: VldParse> VldQuery<T> {
pub(super) async fn extract(
req: &HttpRequest,
_payload: &mut Payload,
) -> Result<Self, VldNtexError> {
validate(&query_string_to_json(req.query_string())).map(VldQuery)
}
}
pub struct VldPath<T>(pub T);
impl<T: VldParse> VldPath<T> {
pub(super) async fn extract(
req: &HttpRequest,
_payload: &mut Payload,
) -> Result<Self, VldNtexError> {
validate(&path_params_to_json(req.match_info().iter())).map(VldPath)
}
}
pub struct VldForm<T>(pub T);
impl<T: VldParse> VldForm<T> {
pub(super) async fn extract(
req: &HttpRequest,
payload: &mut Payload,
) -> Result<Self, VldNtexError> {
require_form_content_type(content_type(req))?;
let body = read_body(req, payload).await?;
validate(&parse_form_body(&body)?).map(VldForm)
}
}
pub struct VldHeaders<T>(pub T);
impl<T: VldParse> VldHeaders<T> {
pub(super) async fn extract(
req: &HttpRequest,
_payload: &mut Payload,
) -> Result<Self, VldNtexError> {
let value = headers_to_json(
req.headers()
.iter()
.map(|(n, v)| (n.as_str(), v.as_bytes())),
);
validate(&value).map(VldHeaders)
}
}
pub struct VldCookie<T>(pub T);
impl<T: VldParse> VldCookie<T> {
pub(super) async fn extract(
req: &HttpRequest,
_payload: &mut Payload,
) -> Result<Self, VldNtexError> {
let value =
cookie_headers_to_json(req.headers().get_all(header::COOKIE).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, VldNtexError, VldPath, VldQuery,
};
pub use vld::prelude::*;
}