use std::future::Future;
use crate::transaction::{Transaction, TransactionError, TransactionHook};
pub struct ClosureHook<C, L> {
closure: Option<C>,
_lifecycle: L,
}
impl<C, L> ClosureHook<C, L> {
pub fn new(closure: C, lifecycle: L) -> Self
where
Self: TransactionHook,
{
Self {
closure: Some(closure),
_lifecycle: lifecycle,
}
}
}
pub struct PreCommit;
pub struct PostCommit;
pub struct OnRollback;
impl<T, F> TransactionHook for ClosureHook<T, PreCommit>
where
T: FnOnce() -> F + Send + 'static,
F: Future<Output = Result<(), TransactionError>> + Send,
{
async fn pre_commit(&mut self, _tx: &mut Transaction) -> Result<(), TransactionError> {
if let Some(closure) = self.closure.take() {
closure().await?;
}
Ok(())
}
}
impl<T> TransactionHook for ClosureHook<T, PostCommit>
where
T: FnOnce() + Send + 'static,
{
fn post_commit(&mut self) {
if let Some(closure) = self.closure.take() {
closure()
}
}
}
impl<T> TransactionHook for ClosureHook<T, OnRollback>
where
T: FnOnce() + Send + 'static,
{
fn on_rollback(&mut self) {
if let Some(closure) = self.closure.take() {
closure()
}
}
}