67 lines
2 KiB
Rust
67 lines
2 KiB
Rust
use std::{error::Error, sync::Arc};
|
|
|
|
use recipes::{app, config, data::db, email, log};
|
|
|
|
pub mod mock_email;
|
|
|
|
pub async fn common_state() -> Result<app::AppState, Box<dyn Error>> {
|
|
common_state_with_email_service(mock_email::new_mock_email_service()).await
|
|
}
|
|
|
|
pub async fn common_state_with_email_service(
|
|
email_service: Arc<dyn email::EmailServiceTrait>,
|
|
) -> Result<app::AppState, Box<dyn Error>> {
|
|
let db_connection = db::Connection::new_in_memory().await?;
|
|
let config = config::Config::default();
|
|
let log = log::Log::new_to_stdout_only_with_max_level(Some(tracing::Level::ERROR));
|
|
Ok(app::AppState {
|
|
config,
|
|
db_connection,
|
|
log,
|
|
email_service,
|
|
})
|
|
}
|
|
|
|
pub async fn create_user(
|
|
db_connection: &db::Connection,
|
|
email: &str,
|
|
password: &str,
|
|
) -> Result<i64, Box<dyn Error>> {
|
|
if let db::user::SignUpResult::UserCreatedWaitingForValidation(token) = db_connection
|
|
.sign_up(email, password, chrono::Weekday::Mon)
|
|
.await?
|
|
{
|
|
if let db::user::ValidationResult::Ok(_, user_id) = db_connection
|
|
.validation(&token, chrono::Duration::hours(1), "", "")
|
|
.await?
|
|
{
|
|
Ok(user_id)
|
|
} else {
|
|
Err(Box::<dyn Error>::from("Unable to validate user"))
|
|
}
|
|
} else {
|
|
Err(Box::<dyn Error>::from("Unable to sign up"))
|
|
}
|
|
}
|
|
|
|
pub async fn sign_in(
|
|
db_connection: &db::Connection,
|
|
email: &str,
|
|
password: &str,
|
|
) -> Result<String, Box<dyn Error>> {
|
|
match db_connection.sign_in(email, password, "", "").await? {
|
|
db::user::SignInResult::Ok(token, _) => Ok(token),
|
|
_ => Err(Box::<dyn Error>::from("Unable to sign in")),
|
|
}
|
|
}
|
|
|
|
pub async fn create_recipe(
|
|
db_connection: &db::Connection,
|
|
user_id: i64,
|
|
title: &str,
|
|
) -> Result<i64, Box<dyn Error>> {
|
|
let recipe_id = db_connection.create_recipe(user_id).await?;
|
|
db_connection.set_recipe_title(recipe_id, title).await?;
|
|
db_connection.set_recipe_is_public(recipe_id, true).await?;
|
|
Ok(recipe_id)
|
|
}
|