Add frontend tests and other stuff
This commit is contained in:
parent
d28e765e39
commit
642dd8a80c
26 changed files with 730 additions and 85 deletions
|
|
@ -49,17 +49,17 @@ fn combine_errors<T>(error: std::result::Result<std::result::Result<T, DBAsyncEr
|
|||
type Result<T> = std::result::Result<T, DBAsyncError>;
|
||||
|
||||
impl Connection {
|
||||
pub async fn get_all_recipe_titles_async(&self) -> Result<Vec<(i32, String)>> {
|
||||
pub async fn get_all_recipe_titles_async(&self) -> Result<Vec<(i64, String)>> {
|
||||
let self_copy = self.clone();
|
||||
web::block(move || { self_copy.get_all_recipe_titles().unwrap_or_default() }).await.map_err(DBAsyncError::from)
|
||||
}
|
||||
|
||||
pub async fn get_recipe_async(&self, id: i32) -> Result<model::Recipe> {
|
||||
pub async fn get_recipe_async(&self, id: i64) -> Result<model::Recipe> {
|
||||
let self_copy = self.clone();
|
||||
combine_errors(web::block(move || { self_copy.get_recipe(id).map_err(DBAsyncError::from) }).await)
|
||||
}
|
||||
|
||||
pub async fn load_user_async(&self, user_id: i32) -> Result<User> {
|
||||
pub async fn load_user_async(&self, user_id: i64) -> Result<User> {
|
||||
let self_copy = self.clone();
|
||||
combine_errors(web::block(move || { self_copy.load_user(user_id).map_err(DBAsyncError::from) }).await)
|
||||
}
|
||||
|
|
@ -101,4 +101,15 @@ impl Connection {
|
|||
let token_copy = token.to_string();
|
||||
combine_errors(web::block(move || { self_copy.sign_out(&token_copy).map_err(DBAsyncError::from) }).await)
|
||||
}
|
||||
|
||||
pub async fn create_recipe_async(&self, user_id: i64) -> Result<i64> {
|
||||
let self_copy = self.clone();
|
||||
combine_errors(web::block(move || { self_copy.create_recipe(user_id).map_err(DBAsyncError::from) }).await)
|
||||
}
|
||||
|
||||
pub async fn set_recipe_title_async(&self, recipe_id: i64, title: &str) -> Result<()> {
|
||||
let self_copy = self.clone();
|
||||
let title_copy = title.to_string();
|
||||
combine_errors(web::block(move || { self_copy.set_recipe_title(recipe_id, &title_copy).map_err(DBAsyncError::from) }).await)
|
||||
}
|
||||
}
|
||||
|
|
@ -60,7 +60,7 @@ pub enum SignUpResult {
|
|||
pub enum ValidationResult {
|
||||
UnknownUser,
|
||||
ValidationExpired,
|
||||
Ok(String, i32), // Returns token and user id.
|
||||
Ok(String, i64), // Returns token and user id.
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -68,18 +68,17 @@ pub enum SignInResult {
|
|||
UserNotFound,
|
||||
WrongPassword,
|
||||
AccountNotValidated,
|
||||
Ok(String, i32), // Returns token and user id.
|
||||
Ok(String, i64), // Returns token and user id.
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AuthenticationResult {
|
||||
NotValidToken,
|
||||
Ok(i32), // Returns user id.
|
||||
Ok(i64), // Returns user id.
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Connection {
|
||||
//con: rusqlite::Connection
|
||||
pool: Pool<SqliteConnectionManager>
|
||||
}
|
||||
|
||||
|
|
@ -106,13 +105,13 @@ impl Connection {
|
|||
fn create_connection(manager: SqliteConnectionManager) -> Result<Connection> {
|
||||
let pool = r2d2::Pool::new(manager).unwrap();
|
||||
let connection = Connection { pool };
|
||||
connection.create_or_update()?;
|
||||
connection.create_or_update_db()?;
|
||||
Ok(connection)
|
||||
}
|
||||
|
||||
/// Called after the connection has been established for creating or updating the database.
|
||||
/// The 'Version' table tracks the current state of the database.
|
||||
fn create_or_update(&self) -> Result<()> {
|
||||
fn create_or_update_db(&self) -> Result<()> {
|
||||
// Check the Database version.
|
||||
let mut con = self.pool.get()?;
|
||||
let tx = con.transaction()?;
|
||||
|
|
@ -174,12 +173,12 @@ impl Connection {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn get_all_recipe_titles(&self) -> Result<Vec<(i32, String)>> {
|
||||
pub fn get_all_recipe_titles(&self) -> Result<Vec<(i64, String)>> {
|
||||
let con = self.pool.get()?;
|
||||
|
||||
let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;
|
||||
|
||||
let titles: std::result::Result<Vec<(i32, String)>, rusqlite::Error> =
|
||||
let titles: std::result::Result<Vec<(i64, String)>, rusqlite::Error> =
|
||||
stmt.query_map([], |row| {
|
||||
Ok((row.get("id")?, row.get("title")?))
|
||||
})?.collect();
|
||||
|
|
@ -198,7 +197,7 @@ impl Connection {
|
|||
Ok(recipes)
|
||||
} */
|
||||
|
||||
pub fn get_recipe(&self, id: i32) -> Result<model::Recipe> {
|
||||
pub fn get_recipe(&self, id: i64) -> Result<model::Recipe> {
|
||||
let con = self.pool.get()?;
|
||||
con.query_row("SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", [id], |row| {
|
||||
Ok(model::Recipe::new(row.get("id")?, row.get("title")?, row.get("description")?))
|
||||
|
|
@ -216,7 +215,7 @@ impl Connection {
|
|||
}).map_err(DBError::from)
|
||||
}
|
||||
|
||||
pub fn load_user(&self, user_id: i32) -> Result<User> {
|
||||
pub fn load_user(&self, user_id: i64) -> Result<User> {
|
||||
let con = self.pool.get()?;
|
||||
con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| {
|
||||
Ok(User {
|
||||
|
|
@ -234,7 +233,7 @@ impl Connection {
|
|||
let tx = con.transaction()?;
|
||||
let token =
|
||||
match tx.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {
|
||||
Ok((r.get::<&str, i32>("id")?, r.get::<&str, Option<String>>("validation_token")?))
|
||||
Ok((r.get::<&str, i64>("id")?, r.get::<&str, Option<String>>("validation_token")?))
|
||||
}).optional()? {
|
||||
Some((id, validation_token)) => {
|
||||
if validation_token.is_none() {
|
||||
|
|
@ -261,7 +260,7 @@ impl Connection {
|
|||
let tx = con.transaction()?;
|
||||
let user_id =
|
||||
match tx.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token], |r| {
|
||||
Ok((r.get::<&str, i32>("id")?, r.get::<&str, DateTime<Utc>>("creation_datetime")?))
|
||||
Ok((r.get::<&str, i64>("id")?, r.get::<&str, DateTime<Utc>>("creation_datetime")?))
|
||||
}).optional()? {
|
||||
Some((id, creation_datetime)) => {
|
||||
if Utc::now() - creation_datetime > validation_time {
|
||||
|
|
@ -283,7 +282,7 @@ impl Connection {
|
|||
let mut con = self.pool.get()?;
|
||||
let tx = con.transaction()?;
|
||||
match tx.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| {
|
||||
Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option<String>>("validation_token")?))
|
||||
Ok((r.get::<&str, i64>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option<String>>("validation_token")?))
|
||||
}).optional()? {
|
||||
Some((id, stored_password, validation_token)) => {
|
||||
if validation_token.is_some() {
|
||||
|
|
@ -306,7 +305,7 @@ impl Connection {
|
|||
let mut con = self.pool.get()?;
|
||||
let tx = con.transaction()?;
|
||||
match tx.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {
|
||||
Ok((r.get::<&str, i32>("id")?, r.get::<&str, i32>("user_id")?))
|
||||
Ok((r.get::<&str, i64>("id")?, r.get::<&str, i64>("user_id")?))
|
||||
}).optional()? {
|
||||
Some((login_id, user_id)) => {
|
||||
tx.execute("UPDATE [UserLoginToken] SET [last_login_datetime] = ?2, [ip] = ?3, [user_agent] = ?4 WHERE [id] = ?1", params![login_id, Utc::now(), ip, user_agent])?;
|
||||
|
|
@ -322,7 +321,7 @@ impl Connection {
|
|||
let mut con = self.pool.get()?;
|
||||
let tx = con.transaction()?;
|
||||
match tx.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| {
|
||||
Ok(r.get::<&str, i32>("id")?)
|
||||
Ok(r.get::<&str, i64>("id")?)
|
||||
}).optional()? {
|
||||
Some(login_id) => {
|
||||
tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?;
|
||||
|
|
@ -333,6 +332,33 @@ impl Connection {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_recipe(&self, user_id: i64) -> Result<i64> {
|
||||
let con = self.pool.get()?;
|
||||
|
||||
// Verify if an empty recipe already exists. Returns its id if one exists.
|
||||
match con.query_row(
|
||||
"SELECT [Recipe].[id] FROM [Recipe]
|
||||
INNER JOIN [Image] ON [Image].[recipe_id] = [Recipe].[id]
|
||||
INNER JOIN [Group] ON [Group].[recipe_id] = [Recipe].[id]
|
||||
WHERE [Recipe].[user_id] = ?1 AND [Recipe].[estimate_time] = NULL AND [Recipe].[description] = NULL",
|
||||
[user_id],
|
||||
|r| {
|
||||
Ok(r.get::<&str, i64>("id")?)
|
||||
}
|
||||
).optional()? {
|
||||
Some(recipe_id) => Ok(recipe_id),
|
||||
None => {
|
||||
con.execute("INSERT INTO [Recipe] ([user_id], [title]) VALUES (?1, '')", [user_id])?;
|
||||
Ok(con.last_insert_rowid())
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_recipe_title(&self, recipe_id: i64, title: &str) -> Result<()> {
|
||||
let con = self.pool.get()?;
|
||||
con.execute("UPDATE [Recipe] SET [title] = ?2 WHERE [id] = ?1", params![recipe_id, title]).map(|_n| ()).map_err(DBError::from)
|
||||
}
|
||||
|
||||
/// Execute a given SQL file.
|
||||
pub fn execute_file<P: AsRef<Path> + fmt::Display>(&self, file: P) -> Result<()> {
|
||||
let con = self.pool.get()?;
|
||||
|
|
@ -348,7 +374,7 @@ impl Connection {
|
|||
}
|
||||
|
||||
// Return the token.
|
||||
fn create_login_token(tx: &rusqlite::Transaction, user_id: i32, ip: &str, user_agent: &str) -> Result<String> {
|
||||
fn create_login_token(tx: &rusqlite::Transaction, user_id: i64, ip: &str, user_agent: &str) -> Result<String> {
|
||||
let token = generate_token();
|
||||
tx.execute("INSERT INTO [UserLoginToken] ([user_id], [last_login_datetime], [token], [ip], [user_agent]) VALUES (?1, ?2, ?3, ?4, ?5)", params![user_id, Utc::now(), token, ip, user_agent])?;
|
||||
Ok(token)
|
||||
|
|
@ -369,6 +395,7 @@ fn generate_token() -> String {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rusqlite::{Error, ErrorCode, ffi, types::Value};
|
||||
|
||||
#[test]
|
||||
fn sign_up() -> Result<()> {
|
||||
|
|
@ -603,4 +630,37 @@ mod tests {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn create_a_new_recipe_then_update_its_title() -> Result<()> {
|
||||
let connection = Connection::new_in_memory()?;
|
||||
|
||||
connection.execute_sql(
|
||||
"INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token]) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
|
||||
params![
|
||||
1,
|
||||
"paul@atreides.com",
|
||||
"paul",
|
||||
"$argon2id$v=19$m=4096,t=3,p=1$G4fjepS05MkRbTqEImUdYg$GGziE8uVQe1L1oFHk37lBno10g4VISnVqynSkLCH3Lc",
|
||||
"2022-11-29 22:05:04.121407300+00:00",
|
||||
Value::Null,
|
||||
]
|
||||
)?;
|
||||
|
||||
match connection.create_recipe(2) {
|
||||
Err(DBError::SqliteError(Error::SqliteFailure(ffi::Error { code: ErrorCode::ConstraintViolation, extended_code: _ }, Some(_)))) => (), // Nominal case.
|
||||
other => panic!("Creating a recipe with an inexistant user must fail: {:?}", other),
|
||||
}
|
||||
|
||||
let recipe_id = connection.create_recipe(1)?;
|
||||
assert_eq!(recipe_id, 1);
|
||||
|
||||
connection.set_recipe_title(recipe_id, "Crêpe")?;
|
||||
|
||||
let recipe = connection.get_recipe(recipe_id)?;
|
||||
assert_eq!(recipe.title, "Crêpe".to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue