2022-04-14 21:40:26 +02:00
|
|
|
use actix::{Actor, Context};
|
|
|
|
use sqlx::PgPool;
|
|
|
|
|
2022-04-16 06:58:48 +02:00
|
|
|
pub use account_orders::*;
|
2022-04-14 21:40:26 +02:00
|
|
|
pub use accounts::*;
|
2022-04-16 07:31:19 +02:00
|
|
|
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::*;
|
2022-04-15 17:04:23 +02:00
|
|
|
pub use stocks::*;
|
2022-04-14 21:40:26 +02:00
|
|
|
|
2022-04-16 06:58:48 +02:00
|
|
|
mod account_orders;
|
2022-04-14 21:40:26 +02:00
|
|
|
mod accounts;
|
2022-04-16 07:31:19 +02:00
|
|
|
mod order_items;
|
2022-04-14 21:40:26 +02:00
|
|
|
mod products;
|
2022-04-16 09:30:11 +02:00
|
|
|
mod shopping_carts;
|
2022-04-15 17:04:23 +02:00
|
|
|
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}")]
|
2022-04-16 06:58:48 +02:00
|
|
|
AccountOrder(account_orders::Error),
|
|
|
|
#[error("{0}")]
|
2022-04-14 21:40:26 +02:00
|
|
|
Product(products::Error),
|
2022-04-15 17:04:23 +02:00
|
|
|
#[error("{0}")]
|
|
|
|
Stock(stocks::Error),
|
2022-04-16 07:31:19 +02:00
|
|
|
#[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>;
|
|
|
|
}
|