Skip to main content

Module common

Module common 

Source
Expand description

Shared HTTP helpers for the vld web integrations.

The common parsing helpers and the shared VldHttpError type used by every framework module of this crate.

Applications normally use it through a framework module. Use it directly to write an adapter for another framework or to build the same error body by hand. It is framework-agnostic: no HTTP framework or http crate dependency.

Guide: https://s00d.github.io/vld/integrations/web/common (the rules below, per framework: https://s00d.github.io/vld/integrations/web/overview).

§Example

use vld_web::common::{parse_json_body, require_json_content_type, VldHttpError};

vld::schema! {
    #[derive(Debug)]
    pub struct User {
        pub name: String => vld::string().min(2),
    }
}

fn extract(content_type: Option<&str>, body: &[u8]) -> Result<User, VldHttpError> {
    require_json_content_type(content_type)?; // 415
    let value = parse_json_body(body)?;       // 422 on malformed JSON
    Ok(User::parse_value(&value)?)            // 422 on validation errors
}

let err = extract(Some("application/json"), br#"{"name": "A"}"#).unwrap_err();
assert_eq!(err.status(), 422);
assert_eq!(err.body()["issues"][0]["code"], "too_small");
assert_eq!(extract(Some("text/plain"), b"{}").unwrap_err().status(), 415);

// Text sources (query, form, path, headers, cookies) use `parse_coerced`.
vld::schema! {
    #[derive(Debug)]
    pub struct Search {
        pub q: String => vld::string(),
        pub page: i64 => vld::number().int().min(1),
        pub tags: Vec<String> => vld::array(vld::string()),
    }
}

let value = vld_web::common::query_string_to_json("q=123&page=2&tags=a");
let s: Search = vld_web::common::parse_coerced(&value).unwrap();
assert_eq!((s.q.as_str(), s.page, s.tags.len()), ("123", 2, 1));

§Value semantics (all adapters)

  • Query strings and form bodies: repeated keys (a=1&a=2) and a[]=1 become arrays; ?flag and ?x= become "".
  • Values are coerced with coerce_value, which never loses information.
  • Coerced sources are validated with parse_coerced: a coerced number / boolean is turned back into text where the schema expects a string (?q=123 into vld::string() is "123"), and a single value is wrapped into an array where the schema expects one (?tags=a).
  • JSON body extractors require a JSON Content-Type (application/json or application/*+json, see is_json_content_type) and form extractors application/x-www-form-urlencoded (require_form_content_type); a missing or different type is 415 {"error": "Unsupported Media Type", "message": ...}.
  • Malformed bodies (JSON, non-UTF-8 forms, more than MAX_FORM_FIELDS form fields) → 422 with the ValidationErrorBody shape; oversized bodies → 413 {"error": "Payload too large"}.
  • Header names containing _ are ignored (see headers_to_json); all Cookie headers are read and the first occurrence of a cookie name wins (see cookie_headers_to_json).

§Error bodies

StatusBody
422{"error": "Validation failed", "issues": [{"path": ".name", "message": "...", "code": "too_small"}]}
413{"error": "Payload too large"}
415{"error": "Unsupported Media Type", "message": "Expected Content-Type: ..."}

path is "" for the root (e.g. malformed JSON), .field for fields and [0] for array items (.items[0].name); code is IssueCode::key().

Structs§

ErrorBody
Simple error body: { "error": "..." }.
ErrorWithMessage
Error body with a message: { "error": "...", "message": "..." }.
ValidationErrorBody
Validation error response body: { "error": "Validation failed", "issues": [...] }.
ValidationIssue
A single validation issue: { "path": "...", "message": "...", "code": "..." } (code is IssueCode::key()).
VldBodyLimit
Body size limit in bytes, registered as request/app data for the adapters without a framework-native body limit setting (vld-actix app_data, vld-ntex app state, vld-poem .data(..); vld-rama has its own extension type).
VldHttpError
Framework-independent error produced by all vld HTTP adapters.

Constants§

DEFAULT_BODY_LIMIT
Default max request body size (2 MiB — same as axum DefaultBodyLimit).
MAX_FORM_FIELDS
Max number of &-separated fields in a form body (parse_form_body).
UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE
Message of the 415 body and error for form extractors.
UNSUPPORTED_MEDIA_TYPE_MESSAGE
Message of the 415 body and error for JSON extractors.

Functions§

coerce_value
Coerce a raw string value (query, form, path, header, cookie) into JSON: the core vld::schema::coerce_text (same rules, one implementation). Coerce a raw text value (query string, form field, path param, header, cookie, environment variable) into JSON, for parse_coerced.
cookie_headers_to_json
Build a JSON object from all Cookie header values of a request.
cookies_to_json
Build a JSON object from a Cookie header value.
format_generic_error
Build a generic JSON error body with a custom error string.
format_issues
Format a VldError into a list of ValidationIssue structs.
format_payload_too_large
Build a JSON error body for payloads that exceed the size limit.
format_unsupported_media_type
Build the JSON error body for a non-JSON Content-Type.
format_vld_error
Format a VldError into a JSON object with "error" and "issues" keys — ready to be sent as a 422 response body.
headers_to_json
Build a JSON object from HTTP header name/value pairs.
is_json_content_type
true for application/json and any application/<x>+json media type with a non-empty <x> (case-insensitive; parameters such as ; charset=utf-8 are ignored, even malformed ones).
parse_coerced
Parse a value whose leaves were coerced from text ("42" → 42, "true" → true), undoing the coercion where the schema disagrees.
parse_form_body
Parse an application/x-www-form-urlencoded body.
parse_json_body
Parse a JSON body; malformed JSON is a 422 parse error.
parse_query_string
Parse a URL query string (or application/x-www-form-urlencoded body) into a serde_json::Map.
path_params_to_json
Build a JSON object from already-decoded path parameters, coercing each value via coerce_value.
percent_decode
Percent-decode a URL component (path segment, cookie value); + is kept.
query_string_to_json
Parse a URL query string into a serde_json::Value::Object.
require_form_content_type
Check the Content-Type of a form body: Ok for application/x-www-form-urlencoded (case-insensitive, parameters allowed), otherwise a 415 error (also when the header is missing or not valid UTF-8).
require_json_content_type
Check the Content-Type of a JSON body: Ok for JSON media types (is_json_content_type), otherwise a 415 error (also when the header is missing or not valid UTF-8).
url_decode
Decode a form/query component: + → space, then percent_decode.