Skip to main content

Module async_graphql

Module async_graphql 

Source
Expand description

§vld_web::async_graphql — async-graphql 7 integration for vld

Validate GraphQL input objects (and any other input value) with vld schemas. The input is converted to JSON (InputType::to_value → ConstValue::into_json) and parsed by the schema S; issues end up in the error’s extensions.issues with the same {"path", "message", "code"} shape as the HTTP 422 body.

ItemUse case
VldValidator<S>#[graphql(validator(custom = "VldValidator::<S>::new()"))] on an argument or input field
validateValidate inside a resolver: validate::<S, _>(&input)?
vld_errorTurn a VldError into an async_graphql::Error with extensions.issues

§Example

use async_graphql::{EmptyMutation, EmptySubscription, InputObject, Object, Schema};
use vld_web::async_graphql::VldValidator;

#[derive(InputObject)]
struct NewUser {
    name: String,
    email: String,
}

// The rules, as a vld schema mirroring the input's JSON.
vld::schema! {
    pub struct NewUserRules {
        pub name: String => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

struct Query;

#[Object]
impl Query {
    async fn register(
        &self,
        #[graphql(validator(custom = "VldValidator::<NewUserRules>::new()"))] user: NewUser,
    ) -> String {
        user.name
    }
}

let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let res = schema
    .execute(r#"{ register(user: {name: "A", email: "bad"}) }"#)
    .await;
let issues = res.errors[0].extensions.as_ref().unwrap().get("issues").unwrap();
assert_eq!(issues.clone().into_json().unwrap()[0]["path"], ".name");

Guide: https://s00d.github.io/vld/integrations/web/async-graphql

Modules§

prelude
Prelude — import everything you need.

Structs§

VldValidator
A CustomValidator checking an input value against the vld schema S.

Functions§

validate
Validate an input value against the vld schema S inside a resolver.
vld_error
An async_graphql::Error with message "Validation failed" and extensions.issues: [{"path": ".name", "message": "...", "code": "too_small"}], the issues of the HTTP 422 body.