1use std::convert::Infallible;
4use std::fmt;
5use std::marker::PhantomData;
6
7use crate::common::{DEFAULT_BODY_LIMIT, is_json_content_type, parse_json_body};
8use rama::extensions::{Extension, ExtensionsRef};
9use rama::http::body::util::BodyExt;
10use rama::http::header;
11use rama::http::{Body, Request, Response};
12use rama::{Layer, Service};
13use vld::schema::VldParse;
14
15use crate::rama::rejection::VldRejection;
16
17#[derive(Clone)]
20pub struct Validated<T>(pub T);
21
22impl<T: fmt::Debug> fmt::Debug for Validated<T> {
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 f.debug_tuple("Validated").field(&self.0).finish()
25 }
26}
27
28impl<T> std::ops::Deref for Validated<T> {
29 type Target = T;
30 fn deref(&self) -> &Self::Target {
31 &self.0
32 }
33}
34
35impl<T: fmt::Debug + Send + Sync + 'static> Extension for Validated<T> {}
36
37#[derive(Clone)]
47pub struct ValidateJsonLayer<T> {
48 limit: usize,
49 _marker: PhantomData<fn() -> T>,
50}
51
52impl<T> ValidateJsonLayer<T> {
53 #[must_use]
56 pub fn new() -> Self {
57 Self::with_limit(DEFAULT_BODY_LIMIT)
58 }
59
60 #[must_use]
62 pub fn with_limit(limit: usize) -> Self {
63 Self {
64 limit,
65 _marker: PhantomData,
66 }
67 }
68}
69
70impl<T> Default for ValidateJsonLayer<T> {
71 fn default() -> Self {
72 Self::new()
73 }
74}
75
76impl<S, T> Layer<S> for ValidateJsonLayer<T> {
77 type Service = ValidateJsonService<S, T>;
78
79 fn layer(&self, inner: S) -> Self::Service {
80 ValidateJsonService {
81 inner,
82 limit: self.limit,
83 _marker: PhantomData,
84 }
85 }
86}
87
88#[derive(Clone)]
90pub struct ValidateJsonService<S, T> {
91 inner: S,
92 limit: usize,
93 _marker: PhantomData<fn() -> T>,
94}
95
96impl<S, T> Service<Request> for ValidateJsonService<S, T>
97where
98 S: Service<Request, Output = Response, Error = Infallible>,
99 T: VldParse + Clone + fmt::Debug + Send + Sync + 'static,
100{
101 type Output = Response;
102 type Error = Infallible;
103
104 async fn serve(&self, req: Request) -> Result<Self::Output, Self::Error> {
105 use rama::http::service::web::response::IntoResponse;
106
107 let is_json = req
108 .headers()
109 .get(header::CONTENT_TYPE)
110 .and_then(|v| v.to_str().ok())
111 .is_some_and(is_json_content_type);
112
113 if !is_json {
114 return self.inner.serve(req).await;
115 }
116
117 let (parts, body) = req.into_parts();
118 let bytes = match body.limited(self.limit).collect().await {
119 Ok(collected) => collected.to_bytes(),
120 Err(e) => return Ok(VldRejection::from_body_error(&e).into_response()),
121 };
122
123 let result = parse_json_body(&bytes)
124 .map_err(VldRejection::from)
125 .and_then(|v| T::vld_parse_value(&v).map_err(VldRejection::from_vld));
126
127 match result {
128 Ok(validated) => {
129 let new_req = Request::from_parts(parts, Body::from(bytes));
130 new_req.extensions().insert(Validated(validated));
131 self.inner.serve(new_req).await
132 }
133 Err(rejection) => Ok(rejection.into_response()),
134 }
135 }
136}
137
138#[must_use]
143pub fn validated<T: Clone + fmt::Debug + Send + Sync + 'static>(req: &Request) -> Option<T> {
144 req.extensions()
145 .get_ref::<Validated<T>>()
146 .map(|v| v.0.clone())
147}