Trait async_graphql::validators::InputValueValidator[][src]

pub trait InputValueValidator where
    Self: Sync + Send
{ fn is_valid(&self, _value: &Value) -> Result<(), String> { ... }
fn is_valid_with_extensions(&self, value: &Value) -> Result<(), Error> { ... } }
Expand description

Input value validator

You can create your own input value validator by implementing this trait.

Examples

use async_graphql::*;
use async_graphql::validators::{Email, MAC, IntRange};

struct QueryRoot;

#[Object]
impl QueryRoot {
    // Input is email address
    async fn value1(&self, #[graphql(validator(Email))] email: String) -> i32 {
        unimplemented!()
    }

    // Input is email or MAC address
    async fn value2(&self, #[graphql(validator(or(Email, MAC(colon = "false"))))] email_or_mac: String) -> i32 {
        unimplemented!()
    }

    // Input is integer between 100 and 200
    async fn value3(&self, #[graphql(validator(IntRange(min = "100", max = "200")))] value: i32) -> i32 {
        unimplemented!()
    }
}

Provided methods

Check value is valid, returns the reason for the error if it fails, otherwise None.

If the input type is different from the required type, return Ok(()) directly, and other validators will find this error.

Check value is valid, returns the reason include extensions for the error if it fails, otherwise None.

If the input type is different from the required type, return Ok(()) directly, and other validators will find this error.

Examples:

use async_graphql::validators::InputValueValidator;
use async_graphql::{Value, Error, ErrorExtensions};

pub struct IntGreaterThanZero;

impl InputValueValidator for IntGreaterThanZero {
    fn is_valid_with_extensions(&self, value: &Value) -> Result<(), Error> {
        if let Value::Number(n) = value {
            if let Some(n) = n.as_i64() {
                if n <= 0 {
                    return Err(
                        Error::new("Value must be greater than 0").extend_with(|_, e| e.set("code", 400))
                    );
                }
            }
        }
        Ok(())
    }
}

Implementors