Restructure

Move some code out to other files. Add transaction guard
This commit is contained in:
jude
2023-09-24 13:11:53 +01:00
parent bd1462a00c
commit 4bad1324b9
4 changed files with 85 additions and 46 deletions

View File

@ -0,0 +1,34 @@
use rocket::{
http::Status,
request::{FromRequest, Outcome},
Request, State,
};
use sqlx::Pool;
use crate::Database;
pub(crate) struct Transaction<'a>(sqlx::Transaction<'a, Database>);
#[derive(Debug)]
pub(crate) enum TransactionError {
Error(sqlx::Error),
Missing,
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Transaction<'r> {
type Error = TransactionError;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match request.guard::<&State<Pool<Database>>>().await {
Outcome::Success(pool) => match pool.begin().await {
Ok(transaction) => Outcome::Success(Transaction(transaction)),
Err(e) => {
Outcome::Failure((Status::InternalServerError, TransactionError::Error(e)))
}
},
Outcome::Failure(e) => Outcome::Failure((e.0, TransactionError::Missing)),
Outcome::Forward(f) => Outcome::Forward(f),
}
}
}