vld_web/async_graphql.rs
1//! # `vld_web::async_graphql` — async-graphql 7 integration for `vld`
2//!
3//! Validate GraphQL input objects (and any other input value) with `vld`
4//! schemas. The input is converted to JSON
5//! ([`InputType::to_value`] → `ConstValue::into_json`) and parsed by the
6//! schema `S`; issues end up in the error's `extensions.issues` with the
7//! same `{"path", "message", "code"}` shape as the
8//! [HTTP 422 body](crate::common#error-bodies).
9//!
10//! | Item | Use case |
11//! |---|---|
12//! | [`VldValidator<S>`] | `#[graphql(validator(custom = "VldValidator::<S>::new()"))]` on an argument or input field |
13//! | [`validate`] | Validate inside a resolver: `validate::<S, _>(&input)?` |
14//! | [`vld_error`] | Turn a [`VldError`] into an [`async_graphql::Error`] with `extensions.issues` |
15//!
16//! # Example
17//!
18//! ```
19//! use async_graphql::{EmptyMutation, EmptySubscription, InputObject, Object, Schema};
20//! use vld_web::async_graphql::VldValidator;
21//!
22//! #[derive(InputObject)]
23//! struct NewUser {
24//! name: String,
25//! email: String,
26//! }
27//!
28//! // The rules, as a vld schema mirroring the input's JSON.
29//! vld::schema! {
30//! pub struct NewUserRules {
31//! pub name: String => vld::string().min(2),
32//! pub email: String => vld::string().email(),
33//! }
34//! }
35//!
36//! struct Query;
37//!
38//! #[Object]
39//! impl Query {
40//! async fn register(
41//! &self,
42//! #[graphql(validator(custom = "VldValidator::<NewUserRules>::new()"))] user: NewUser,
43//! ) -> String {
44//! user.name
45//! }
46//! }
47//!
48//! # tokio_test(async {
49//! let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
50//! let res = schema
51//! .execute(r#"{ register(user: {name: "A", email: "bad"}) }"#)
52//! .await;
53//! let issues = res.errors[0].extensions.as_ref().unwrap().get("issues").unwrap();
54//! assert_eq!(issues.clone().into_json().unwrap()[0]["path"], ".name");
55//! # });
56//! # fn tokio_test(f: impl std::future::Future<Output = ()>) {
57//! # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(f)
58//! # }
59//! ```
60//!
61//! Guide: <https://s00d.github.io/vld/integrations/web/async-graphql>
62use std::marker::PhantomData;
63
64use async_graphql::{CustomValidator, ErrorExtensionValues, InputType, InputValueError, Value};
65use vld::error::{IssueCode, VldError};
66use vld::schema::VldParse;
67
68/// Message of every validation error this module builds.
69const MESSAGE: &str = "Validation failed";
70
71/// A `CustomValidator` checking an input value against the vld schema `S`.
72///
73/// `S` is any [`VldParse`] type (a `vld::schema!` struct, a
74/// `#[derive(Validate)]` type) whose rules describe the input's JSON. On
75/// failure the GraphQL error has the message
76/// `Failed to parse "<Input>": Validation failed` (async-graphql adds the
77/// prefix) and `extensions.issues`.
78///
79/// ```ignore
80/// #[graphql(validator(custom = "VldValidator::<NewUserRules>::new()"))] user: NewUser
81/// ```
82pub struct VldValidator<S>(PhantomData<fn() -> S>);
83
84impl<S> VldValidator<S> {
85 /// A validator for the schema `S`.
86 #[must_use]
87 pub const fn new() -> Self {
88 Self(PhantomData)
89 }
90}
91
92impl<S> Default for VldValidator<S> {
93 fn default() -> Self {
94 Self::new()
95 }
96}
97
98impl<S: VldParse, T: InputType> CustomValidator<T> for VldValidator<S> {
99 fn check(&self, value: &T) -> Result<(), InputValueError<T>> {
100 check::<S, T>(value)
101 .map_err(|e| InputValueError::custom(MESSAGE).with_extension("issues", issues(&e)))
102 }
103}
104
105/// Validate an input value against the vld schema `S` inside a resolver.
106///
107/// ```ignore
108/// async fn register(&self, user: NewUser) -> async_graphql::Result<String> {
109/// vld_web::async_graphql::validate::<NewUserRules, _>(&user)?;
110/// Ok(user.name)
111/// }
112/// ```
113pub fn validate<S: VldParse, T: InputType>(value: &T) -> async_graphql::Result<()> {
114 check::<S, T>(value).map_err(|e| vld_error(&e))
115}
116
117/// An [`async_graphql::Error`] with message `"Validation failed"` and
118/// `extensions.issues`: `[{"path": ".name", "message": "...", "code":
119/// "too_small"}]`, the issues of the HTTP 422 body.
120pub fn vld_error(error: &VldError) -> async_graphql::Error {
121 let mut extensions = ErrorExtensionValues::default();
122 extensions.set("issues", issues(error));
123 let mut err = async_graphql::Error::new(MESSAGE);
124 err.extensions = Some(extensions);
125 err
126}
127
128fn check<S: VldParse, T: InputType>(value: &T) -> Result<(), VldError> {
129 let json = value
130 .to_value()
131 .into_json()
132 .map_err(|e| VldError::single(IssueCode::ParseError, format!("Input is not JSON: {e}")))?;
133 S::vld_parse_value(&json).map(drop)
134}
135
136fn issues(error: &VldError) -> Value {
137 let issues = serde_json::to_value(crate::common::format_issues(error))
138 .expect("ValidationIssue serialization cannot fail");
139 Value::from_json(issues).expect("issues are plain JSON")
140}
141
142/// Prelude — import everything you need.
143pub mod prelude {
144 pub use super::{VldValidator, validate, vld_error};
145 pub use vld::prelude::*;
146}