Skip to main content

vld_web/
ntex4.rs

1//! # `vld_web::ntex4` — ntex 4 integration for `vld`
2//!
3//! Provides extractors that validate request data using `vld` schemas:
4//!
5//! | Extractor | Replaces | Source |
6//! |---|---|---|
7//! | [`VldJson<T>`] | `ntex::web::types::Json<T>` | JSON request body |
8//! | [`VldQuery<T>`] | `ntex::web::types::Query<T>` | URL query parameters |
9//! | [`VldPath<T>`] | `ntex::web::types::Path<T>` | URL path parameters |
10//! | [`VldForm<T>`] | `ntex::web::types::Form<T>` | URL-encoded form body |
11//! | [`VldHeaders<T>`] | manual header extraction | HTTP headers |
12//! | [`VldCookie<T>`] | manual cookie parsing | Cookie values |
13//!
14//! All extractors return **422 Unprocessable Entity** on validation failure
15//! or malformed input, and **413 Payload Too Large** when the body exceeds
16//! the limit. [`VldJson`] requires a JSON `Content-Type` (`application/json`
17//! or `application/*+json`) and [`VldForm`]
18//! `application/x-www-form-urlencoded`; anything else is **415 Unsupported
19//! Media Type**. See the [error body format](crate::common#error-bodies).
20//!
21//! Guide: <https://s00d.github.io/vld/integrations/web/ntex> (shared rules
22//! for all adapters: <https://s00d.github.io/vld/integrations/web/overview>).
23//!
24//! # Body limits
25//!
26//! [`VldJson`] and [`VldForm`] read the body themselves up to
27//! [`DEFAULT_BODY_LIMIT`](crate::common::DEFAULT_BODY_LIMIT) (2 MiB); ntex's
28//! `JsonConfig` / `PayloadConfig` do not apply. Register [`VldBodyLimit`] as
29//! app state to change it: `App::new().with_config(WebAppConfig::new().set_value(VldBodyLimit(n)))`. Compressed request bodies are decoded only
30//! with the `ntex-compress` feature (the limit then applies to the decoded
31//! size).
32//!
33//! # ntex versions
34//!
35//! This module is ntex 4 (feature `ntex-4`); `vld_web::ntex3` is the same
36//! adapter for ntex 3 (feature `ntex-3`). Both can be enabled together.
37//! The ntex crate is re-exported as [`ntex`].
38//!
39//! # Example
40//!
41//! ```no_run
42//! use vld_web::ntex4::ntex::web::HttpResponse;
43//! use vld_web::ntex4::{VldJson, VldPath};
44//!
45//! vld::schema! {
46//!     #[derive(Debug)]
47//!     pub struct PathParams {
48//!         pub id: i64 => vld::number().int().min(1),
49//!     }
50//! }
51//!
52//! vld::schema! {
53//!     #[derive(Debug)]
54//!     pub struct Body {
55//!         pub name: String => vld::string().min(2),
56//!     }
57//! }
58//!
59//! async fn handler(
60//!     path: VldPath<PathParams>,
61//!     body: VldJson<Body>,
62//! ) -> HttpResponse {
63//!     HttpResponse::Ok().body(format!("id={} name={}", path.id, body.name))
64//! }
65//!
66//! // Inside `HttpServer::new(...)`:
67//! // App::new().route("/users/{id}", web::post().to(handler))
68//! ```
69
70/// The ntex 4 crate this module is built on.
71pub use ::ntex4 as ntex;
72
73// One implementation, compiled once per ntex major (ARCHITECTURE.md).
74#[allow(clippy::duplicate_mod)]
75#[path = "ntex/shared.rs"]
76mod shared;
77pub use shared::*;
78
79/// ntex 4 glue: error rendering and the `FromRequest` impls (forwarding to
80/// each extractor's inherent `extract`).
81mod compat {
82    use super::ntex;
83    use super::shared::*;
84    use ntex::http::Payload;
85    use ntex::web::FromRequest;
86    use ntex::web::error::WebResponseError;
87    use ntex::web::{HttpRequest, HttpResponse};
88
89    /// A value registered on the app (`app_value` (ntex >= 4.7; `app_state` is deprecated)).
90    pub(super) fn app_value<T: 'static>(req: &HttpRequest) -> Option<&T> {
91        req.app_value::<T>()
92    }
93    use vld::schema::VldParse;
94
95    impl<St, Err> WebResponseError<St, Err> for VldNtexError {
96        fn error_response(&self, _: &St) -> HttpResponse {
97            self.render()
98        }
99    }
100
101    macro_rules! from_request {
102        ($($t:ident),+) => {$(
103            impl<T: VldParse, St> FromRequest<St> for $t<T> {
104                type Error = VldNtexError;
105
106                async fn from_request(
107                    _: &St,
108                    req: &HttpRequest,
109                    payload: &mut Payload,
110                ) -> Result<Self, Self::Error> {
111                    Self::extract(req, payload).await
112                }
113            }
114        )+};
115    }
116
117    from_request!(VldJson, VldQuery, VldPath, VldForm, VldHeaders, VldCookie);
118}