bazzar/api/src/actors/database.rs

76 lines
1.7 KiB
Rust
Raw Normal View History

2022-04-14 21:40:26 +02:00
use actix::{Actor, Context};
use sqlx::PgPool;
pub use account_orders::*;
2022-04-14 21:40:26 +02:00
pub use accounts::*;
pub use order_items::*;
2022-04-14 21:40:26 +02:00
pub use products::*;
2022-04-16 09:30:11 +02:00
pub use shopping_carts::*;
pub use stocks::*;
2022-04-14 21:40:26 +02:00
mod account_orders;
2022-04-14 21:40:26 +02:00
mod accounts;
mod order_items;
2022-04-14 21:40:26 +02:00
mod products;
2022-04-16 09:30:11 +02:00
mod shopping_carts;
mod stocks;
2022-04-14 21:40:26 +02:00
#[macro_export]
macro_rules! async_handler {
($msg: ty, $async: ident, $res: ty) => {
impl Handler<$msg> for Database {
type Result = ResponseActFuture<Self, Result<$res>>;
fn handle(&mut self, msg: $msg, _ctx: &mut Self::Context) -> Self::Result {
let pool = self.pool.clone();
Box::pin(async { $async(msg, pool).await }.into_actor(self))
}
}
};
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Failed to connect to database. {0:?}")]
Connect(sqlx::Error),
#[error("{0}")]
Account(accounts::Error),
#[error("{0}")]
AccountOrder(account_orders::Error),
#[error("{0}")]
2022-04-14 21:40:26 +02:00
Product(products::Error),
#[error("{0}")]
Stock(stocks::Error),
#[error("{0}")]
OrderItem(order_items::Error),
2022-04-16 09:30:11 +02:00
#[error("{0}")]
ShoppingCart(shopping_carts::Error),
2022-04-14 21:40:26 +02:00
}
pub type Result<T> = std::result::Result<T, Error>;
pub struct Database {
pool: PgPool,
}
impl Clone for Database {
fn clone(&self) -> Self {
Self { pool: self.pool.clone() }
}
}
impl Database {
pub(crate) async fn build(url: &str) -> Result<Self> {
let pool = sqlx::PgPool::connect(url).await.map_err(Error::Connect)?;
Ok(Database { pool })
}
pub fn pool(&self) -> &PgPool {
&self.pool
}
}
impl Actor for Database {
type Context = Context<Self>;
}