RouteBinding

Trait RouteBinding 

Source
pub trait RouteBinding: Sized + Send {
    // Required methods
    fn param_name() -> &'static str;
    fn from_route_param<'life0, 'async_trait>(
        value: &'life0 str,
    ) -> Pin<Box<dyn Future<Output = Result<Self, FrameworkError>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait;
}
Expand description

Trait for models that can be automatically resolved from route parameters

Implement this trait on your SeaORM Model types to enable automatic route model binding in handlers. When a route parameter matches the param_name(), the model will be automatically fetched from the database.

If the model is not found, a 404 Not Found response is returned.

§Example

use kit::database::RouteBinding;
use kit::FrameworkError;

#[async_trait]
impl RouteBinding for user::Model {
    fn param_name() -> &'static str {
        "user"  // matches {user} in route like /users/{user}
    }

    async fn from_route_param(value: &str) -> Result<Self, FrameworkError> {
        let id: i32 = value.parse()
            .map_err(|_| FrameworkError::param_parse(value, "i32"))?;

        user::Entity::find_by_pk(id)
            .await?
            .ok_or_else(|| FrameworkError::model_not_found("User"))
    }
}

Required Methods§

Source

fn param_name() -> &'static str

The route parameter name to bind from

This should match the parameter placeholder in your route definition. For example, if your route is /users/{user}, this should return "user".

Source

fn from_route_param<'life0, 'async_trait>( value: &'life0 str, ) -> Pin<Box<dyn Future<Output = Result<Self, FrameworkError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Fetch the model from the database using the route parameter value

This method is called automatically by the #[handler] macro when a parameter of this type is declared in the handler function.

§Returns
  • Ok(Self) - The model was found
  • Err(FrameworkError::ModelNotFound) - Model not found (returns 404)
  • Err(FrameworkError::ParamParse) - Parameter could not be parsed (returns 400)

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§