awpak_rs/parser/from_async_str/
from_async_str.rs

1use std::str::FromStr;
2
3use crate::io::io::IO;
4
5
6/// A trait for asynchronously converting a string into a type.
7///
8/// Implement this trait for types that should be deserialized from URL path variables.
9/// This is useful when fetching database records or performing async lookups based
10/// on URL parameters.
11///
12/// # Example
13///
14/// ```ignore
15/// impl FromAsyncStr<User> for User {
16///     async fn from_async_str(io: &IO, s: &str) -> Result<User, ()> {
17///         let user = get_user_from_db(s).await;
18///         Ok(user)
19///     }
20/// }
21/// ```
22///
23/// This allows extracting a `User` object from a path variable, like in:
24///
25/// ```ignore
26/// #[get(url = "/user/{id}")]
27/// async fn get_user(#[path_variable] user: User) -> User {
28///     user
29/// }
30/// ```
31///
32/// A request like `GET /user/42` will trigger an asynchronous database lookup,
33/// fetching the corresponding `User` object.
34pub trait FromAsyncStr<T>
35{
36    fn from_async_str( io : &IO, s : &str ) -> impl std::future::Future<Output = Result<T, ()>> + Send;
37}
38
39impl<T: FromStr> FromAsyncStr<T> for T
40{
41    async fn from_async_str( _io : &IO, s : &str ) -> Result<T, ()>
42    {
43        match T::from_str( s )
44        {
45            Ok( v ) => Ok( v ),
46            _ => Err( () )
47        }
48    }
49}