Keats/validator

Custom unique username future error

Closed this issue · 3 comments

    #[validate(
        length(min = 4, message = "Username must be greater than 4 chars"),
        regex(
            path = "RE_USERNAME",
            message = "Username must be alphanumeric and/or dashes only"
        ),
        custom(
            function = "username_exists",
            arg = "&'v_a Pool<Postgres>",
            message = "this username already taken"
        )
    )]
    pub username: String,
pub async fn username_exists(username: &str, pool: &Pool<Postgres>) -> Result<(), ValidationError> {
    let res = sqlx::query!("SELECT username FROM users WHERE username = $1", username)
        .fetch_one(pool)
        .await;

    match res {
        Ok(_) => Ok(()),
        Err(_) => return Err(ValidationError::new("Username exists Failed")),
    }
}

the error

error[E0308]: mismatched types
   --> src/handlers/user_handler.rs:100:23
    |
100 | #[derive(Deserialize, Validate, Debug)]
    |                       ^^^^^^^^
    |                       |
    |                       expected future, found `Result<_, _>`
    |                       this expression has type `impl std::future::Future<Output = Result<(), ValidationError>>`
    ```

It doesn't support async functions

so how to check something in db ?

ifui commented

Maybe check in service. Hope support async fun.