Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,93 @@ async fn test_my_ohkami() {
}
```

### DI by generics

```rust,no_run
use ohkami::prelude::*;

//////////////////////////////////////////////////////////////////////
/// errors

enum MyError {
Sqlx(sqlx::Error),
}
impl IntoResponse for MyError {
fn into_response(self) -> Response {
match self {
Self::Sqlx(e) => Response::InternalServerError(),
}
}
}

//////////////////////////////////////////////////////////////////////
/// repository

trait Repository: Send + Sync + 'static {
fn get_user_by_id(
&self,
id: i64,
) -> impl Future<Output = Result<UserRow, MyError>> + Send;
}

#[derive(sqlx::FromRow)]
struct UserRow {
id: i64,
name: String,
}

struct PostgresRepository(sqlx::PgPool);
impl Repository for PostgresRepository {
async fn get_user_by_id(&self, id: i64) -> Result<UserRow, MyError> {
let sql = r#"
SELECT id, name FROM users WHERE id = $1
"#;
sqlx::query_as::<_, UserRow>(sql)
.bind(id)
.fetch_one(&self.0)
.await
.map_err(MyError::Sqlx)
}
}

//////////////////////////////////////////////////////////////////////
/// routes

#[derive(Serialize)]
struct User {
id: u32,
name: String,
}

async fn get_user<R: Repository>(
id: u32,
Context(r): Context<'_, R>,
) -> Result<JSON<User>, MyError> {
let user_row = r.get_user_by_id(id as i64).await?;

Ok(JSON(User {
id: user_row.id as u32,
name: user_row.name,
}))
}

fn users_ohkami<R: Repository>() -> Ohkami {
Ohkami::new((
"/:id".GET(get_user::<R>),
))
}

//////////////////////////////////////////////////////////////////////
/// entry point

#[tokio::main]
async fn main() {
Ohkami::new((
"/users".By(users_ohkami::<PostgresRepository>()),
)).howl("0.0.0.0:4040").await
}
```

<br>

## Supported protocols
Expand Down
2 changes: 1 addition & 1 deletion ohkami/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,4 @@ DEBUG = ["tokio?/rt-multi-thread", "tokio?/macros"]


[dev-dependencies]
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "macros"] }
75 changes: 75 additions & 0 deletions ohkami/src/ohkami/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,81 @@ use crate::{__rt__, Session};
/// }
/// }
/// ```
///
/// <br>
///
/// ## Generics DI
///
/// A way of DI -*Dependency Injection*- is **generics** :
///
/// ```
/// use ohkami::prelude::*;
///
/// # //////////////////////////////////////////////////////////////////////
/// # /// errors
/// #
/// # enum MyError {
/// # Sqlx(sqlx::Error),
/// # }
/// # impl IntoResponse for MyError {
/// # fn into_response(self) -> Response {
/// # match self {
/// # Self::Sqlx(e) => Response::InternalServerError(),
/// # }
/// # }
/// # }
/// #
/// //////////////////////////////////////////////////////////////////////
/// /// repository
///
/// trait Repository: Send + Sync + 'static {
/// fn get_user_name_by_id(
/// &self,
/// id: i64,
/// ) -> impl Future<Output = Result<String, MyError>> + Send;
/// }
///
/// struct PostgresRepository(sqlx::PgPool);
/// impl Repository for PostgresRepository {
/// async fn get_user_name_by_id(&self, id: i64) -> Result<String, MyError> {
/// let sql = r#"
/// SELECT name FROM users WHERE id = $1
/// "#;
/// sqlx::query_scalar::<_, String>(sql)
/// .bind(id)
/// .fetch_one(&self.0)
/// .await
/// .map_err(MyError::Sqlx)
/// }
/// }
///
/// //////////////////////////////////////////////////////////////////////
/// /// routes
///
/// #[derive(Serialize)]
/// struct User {
/// id: u32,
/// name: String,
/// }
///
/// async fn get_user<R: Repository>(
/// id: u32,
/// Context(r): Context<'_, R>,
/// ) -> Result<JSON<User>, MyError> {
/// let user_name = r.get_user_name_by_id(id as i64).await?;
///
/// Ok(JSON(User {
/// id: id as u32,
/// name: user_name,
/// }))
/// }
///
/// fn users_ohkami<R: Repository>() -> Ohkami {
/// Ohkami::new((
/// "/:id".GET(get_user::<R>),
/// ))
/// }
/// ```
pub struct Ohkami {
router: Router,
/// apply just before merged to another, or just before `howl`ing
Expand Down