bazzar/web/src/actors/database.rs

60 lines
1.3 KiB
Rust
Raw Normal View History

2022-04-14 21:40:26 +02:00
use actix::{Actor, Context};
use sqlx::PgPool;
pub use accounts::*;
pub use products::*;
mod accounts;
mod products;
#[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}")]
Product(products::Error),
}
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>;
}