async-graphql/docs/zh-CN/src/input_value_validators.md
Edward Rudd 3b7ed74d11 correct doc examples so they compile
- examples to fix still
  - error_extensions.md ResultExt example does not compile!
     - trait ErrorExtensions is not implemented for ParseIntError
  - dataloader
     - requires sqlx to work. So we either "stub" it OR we rewrite them simpler to use a  simple "faux" db library
2022-06-02 17:32:12 -04:00

2.1 KiB
Raw Blame History

输入值校验器

Async-graphql内置了一些常用的校验器,你可以在对象字段的参数或者InputObject的字段上使用它们。

  • maximum=N 指定数字不能大于N
  • minimum=N 指定数字不能小于N
  • multiple_of=N 指定数字必须是N的倍数
  • max_items=N 指定列表的长度不能大于N
  • min_items=N 指定列表的长度不能小于N
  • max_length=N 字符串的长度不能大于N
  • min_length=N 字符串的长度不能小于N
  • chars_max_length=N 字符串中unicode字符的的数量不能小于N
  • chars_min_length=N 字符串中unicode字符的的数量不能大于N
  • email 有效的email
  • url 有效的url
  • ip 有效的ip地址
  • regex=RE 匹配正则表达式
# extern crate async_graphql;
use async_graphql::*;

struct Query;

#[Object]
impl Query {
    /// name参数的长度必须大于等于5小于等于10
    async fn input(&self, #[graphql(validator(min_length = 5, max_length = 10))] name: String) -> Result<i32> {
#        todo!()    
    }
}

校验列表成员

你可以打开list属性表示校验器作用于一个列表内的所有成员:

# extern crate async_graphql;
use async_graphql::*;

struct Query;

#[Object]
impl Query {
    async fn input(&self, #[graphql(validator(list, max_length = 10))] names: Vec<String>) -> Result<i32> {
#        todo!()
    }
}

自定义校验器

# extern crate async_graphql;
# use async_graphql::*;
struct MyValidator {
    expect: i32,
}

impl MyValidator {
    pub fn new(n: i32) -> Self {
        MyValidator { expect: n }
    }
}

impl CustomValidator<i32> for MyValidator {
    fn check(&self, value: &i32) -> Result<(), String> {
        if *value == self.expect {
            Ok(())
        } else {
            Err(format!("expect 100, actual {}", value))
        }
    }
}

struct Query;

#[Object]
impl Query {
    /// n的值必须等于100
    async fn value(
        &self,
        #[graphql(validator(custom = "MyValidator::new(100)"))] n: i32,
    ) -> i32 {
        n
    }
}