#[database]Expand description
§🛢️ Database Macro
The database macro is a procedural macro that injects a database connection
into repository methods.
It expects two mandatory attributes:
name: selects which configured database connection will be used.error: defines the error variant returned when the database is not configured or database connection cannot be found.
The macro injects a variable named db with type &DatabaseConnection (seaorm),
so the function body can execute queries directly.
Example:
use rust_microservice::{Server, database};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum UserError {
#[error("Database is not configured")]
DatabaseNotConfigured,
#[error("User not found")]
NotFound,
}
pub type Result<T, E = UserError> = std::result::Result<T, E>;
#[database(name = "api", error = "UserError::DatabaseNotConfigured")]
pub async fn get_user_by_id(user_id: i32) -> Result<()> {
// Database will be injected here as `db`
//user::Entity::find_by_id(user_id)
// .one(&db)
// .await
// .map_err(|_| UserError::NotFound)?
// .ok_or(UserError::NotFound)
// .map(Into::into)
Ok(())
}§🛢️ Database Macro
The database macro is a procedural macro that injects a database connection
into repository methods.
It expects two mandatory attributes:
name: selects which configured database connection will be used.error: defines the error variant returned when the database is not configured or database connection cannot be found.
The macro injects a variable named db with type &DatabaseConnection (seaorm),
so the function body can execute queries directly.
Example:
ⓘ
use rust_microservice::{Server, database};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum UserError {
#[error("Database is not configured")]
DatabaseNotConfigured,
#[error("User not found")]
NotFound,
}
pub type Result<T, E = UserError> = std::result::Result<T, E>;
#[database(name = "api", error = "UserError::DatabaseNotConfigured")]
pub async fn get_user_by_id(user_id: i32) -> Result<()> {
// Database will be injected here as `db`
//user::Entity::find_by_id(user_id)
// .one(&db)
// .await
// .map_err(|_| UserError::NotFound)?
// .ok_or(UserError::NotFound)
// .map(Into::into)
Ok(())
}