use std::ops::Deref;
use serde::de::DeserializeOwned;
use validator::Validate;
use crate::web::context::RequestContext;
use crate::web::error::{HttpException, Validation};
use crate::web::extract::{extract_body_json, extract_query};
#[derive(Debug, Clone)]
pub struct Validated<T>(T);
impl<T> Validated<T> {
#[inline]
pub fn into_inner(self) -> T {
self.0
}
#[inline]
pub fn inner(&self) -> &T {
&self.0
}
#[inline]
pub fn assume_valid(v: T) -> Self {
Self(v)
}
}
impl<T> Deref for Validated<T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
&self.0
}
}
impl<T: DeserializeOwned + Validate> Validated<T> {
pub fn from_body(ctx: &RequestContext) -> Result<Self, HttpException> {
let v: T = extract_body_json(ctx)?;
v.validate()
.map_err(|e| HttpException::from(Validation::from(e)))?;
Ok(Self(v))
}
pub fn from_query(ctx: &RequestContext) -> Result<Self, HttpException> {
let v: T = extract_query(ctx)?;
v.validate()
.map_err(|e| HttpException::from(Validation::from(e)))?;
Ok(Self(v))
}
}