From 7a09e2360e1294b12b2127092afde923b35bc1b8 Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Tue, 7 Jan 2025 23:55:16 +0100 Subject: [PATCH] [Database] Add 'creation_datetime' to User + some little things --- backend/sql/data_test.sql | 6 +- backend/sql/version_1.sql | 3 + backend/src/data/{db.rs => db/mod.rs} | 0 backend/src/data/db/recipe.rs | 5 +- backend/src/data/db/user.rs | 21 ++-- backend/src/html_templates.rs | 56 +++++----- backend/src/main.rs | 6 +- backend/src/{services.rs => services/mod.rs} | 4 +- backend/src/services/recipe.rs | 2 +- backend/src/services/user.rs | 106 ++++++++++--------- backend/src/translation.rs | 45 +++----- backend/src/utils.rs | 41 +++++++ frontend/src/handles.rs | 9 +- frontend/src/lib.rs | 6 +- 14 files changed, 179 insertions(+), 131 deletions(-) rename backend/src/data/{db.rs => db/mod.rs} (100%) rename backend/src/{services.rs => services/mod.rs} (95%) diff --git a/backend/sql/data_test.sql b/backend/sql/data_test.sql index a00170c..5f37367 100644 --- a/backend/sql/data_test.sql +++ b/backend/sql/data_test.sql @@ -1,18 +1,20 @@ -INSERT INTO [User] ([id], [email], [name], [password], [validation_token_datetime], [validation_token]) +INSERT INTO [User] ([id], [email], [name], [creation_datetime], [password], [validation_token_datetime], [validation_token]) VALUES ( 1, 'paul@atreides.com', 'Paul', + '2025-01-07T10:41:05.697884837+00:00', '$argon2id$v=19$m=4096,t=4,p=2$l1fAMRc0VfkNzqpEfFEReg$/gsUsY2aML8EbKjPeCxucenxkxhiFSXDmizWZPLvNuo', 0, NULL ); -INSERT INTO [User] ([id], [email], [name], [password], [validation_token_datetime], [validation_token]) +INSERT INTO [User] ([id], [email], [name], [creation_datetime], [password], [validation_token_datetime], [validation_token]) VALUES ( 2, 'alia@atreides.com', 'Alia', + '2025-01-07T10:41:05.697884837+00:00', '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY', 0, NULL diff --git a/backend/sql/version_1.sql b/backend/sql/version_1.sql index 76c96cd..306f195 100644 --- a/backend/sql/version_1.sql +++ b/backend/sql/version_1.sql @@ -7,8 +7,11 @@ CREATE TABLE [Version] ( CREATE TABLE [User] ( [id] INTEGER PRIMARY KEY, + [email] TEXT NOT NULL, [name] TEXT NOT NULL DEFAULT '', + [creation_datetime] TEXT NOT NULL, + [default_servings] INTEGER DEFAULT 4, [lang] TEXT NOT NULL DEFAULT 'en', diff --git a/backend/src/data/db.rs b/backend/src/data/db/mod.rs similarity index 100% rename from backend/src/data/db.rs rename to backend/src/data/db/mod.rs diff --git a/backend/src/data/db/recipe.rs b/backend/src/data/db/recipe.rs index 48a94f9..1dc5c8f 100644 --- a/backend/src/data/db/recipe.rs +++ b/backend/src/data/db/recipe.rs @@ -628,14 +628,15 @@ mod tests { sqlx::query( r#" INSERT INTO [User] - ([id], [email], [name], [password], [validation_token_datetime], [validation_token]) + ([id], [email], [name], [creation_datetime], [password], [validation_token_datetime], [validation_token]) VALUES - ($1, $2, $3, $4, $5, $6) + ($1, $2, $3, $4, $5, $6, $7) "# ) .bind(user_id) .bind("paul@atreides.com") .bind("paul") + .bind("") .bind("$argon2id$v=19$m=4096,t=3,p=1$G4fjepS05MkRbTqEImUdYg$GGziE8uVQe1L1oFHk37lBno10g4VISnVqynSkLCH3Lc") .bind("2022-11-29 22:05:04.121407300+00:00") .bind(None::<&str>) // 'null'. diff --git a/backend/src/data/db/user.rs b/backend/src/data/db/user.rs index b960379..446bdf5 100644 --- a/backend/src/data/db/user.rs +++ b/backend/src/data/db/user.rs @@ -222,11 +222,12 @@ WHERE [id] = $1 sqlx::query( r#" INSERT INTO [User] -([email], [validation_token], [validation_token_datetime], [password]) -VALUES ($1, $2, $3, $4) +([email], [creation_datetime], [validation_token], [validation_token_datetime], [password]) +VALUES ($1, $2, $3, $4, $5) "#, ) .bind(email) + .bind(Utc::now()) .bind(&token) .bind(datetime) .bind(hashed_password) @@ -509,11 +510,12 @@ mod tests { sqlx::query( r#" INSERT INTO - [User] ([id], [email], [name], [password], [validation_token_datetime], [validation_token]) + [User] ([id], [email], [name], [creation_datetime], [password], [validation_token_datetime], [validation_token]) VALUES ( 1, 'paul@atreides.com', 'paul', + '', '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY', 0, NULL @@ -557,10 +559,11 @@ INSERT INTO sqlx::query( r#" INSERT INTO [User] - ([id], [email], [name], [password], [validation_token_datetime], [validation_token]) + ([id], [email], [creation_datetime], [name], [password], [validation_token_datetime], [validation_token]) VALUES ( 1, 'paul@atreides.com', + '', 'paul', '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY', 0, @@ -896,17 +899,11 @@ VALUES ( sqlx::query( r#" INSERT INTO [User] - ([id], [email], [name], [password], [validation_token_datetime], [validation_token]) + ([id], [email], [name], [creation_datetime], [password], [validation_token_datetime], [validation_token]) VALUES - ($1, $2, $3, $4, $5, $6) + (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', NULL) "# ) - .bind(1) - .bind("paul@atreides.com") - .bind("paul") - .bind("$argon2id$v=19$m=4096,t=3,p=1$G4fjepS05MkRbTqEImUdYg$GGziE8uVQe1L1oFHk37lBno10g4VISnVqynSkLCH3Lc") - .bind("2022-11-29 22:05:04.121407300+00:00") - .bind(None::<&str>) // 'null'. ).await?; let user = connection.load_user(1).await?.unwrap(); diff --git a/backend/src/html_templates.rs b/backend/src/html_templates.rs index 1679e6a..a1fb570 100644 --- a/backend/src/html_templates.rs +++ b/backend/src/html_templates.rs @@ -28,16 +28,16 @@ pub struct HomeTemplate { #[derive(Template)] #[template(path = "message.html")] -pub struct MessageTemplate { +pub struct MessageTemplate<'a> { pub user: Option, pub tr: Tr, - pub message: String, + pub message: &'a str, pub as_code: bool, // Display the message in
 markup.
 }
 
-impl MessageTemplate {
-    pub fn new(message: String, tr: Tr) -> MessageTemplate {
+impl<'a> MessageTemplate<'a> {
+    pub fn new(message: &'a str, tr: Tr) -> MessageTemplate<'a> {
         MessageTemplate {
             user: None,
             tr,
@@ -46,7 +46,11 @@ impl MessageTemplate {
         }
     }
 
-    pub fn new_with_user(message: String, tr: Tr, user: Option) -> MessageTemplate {
+    pub fn new_with_user(
+        message: &'a str,
+        tr: Tr,
+        user: Option,
+    ) -> MessageTemplate<'a> {
         MessageTemplate {
             user,
             tr,
@@ -58,59 +62,59 @@ impl MessageTemplate {
 
 #[derive(Template)]
 #[template(path = "sign_up_form.html")]
-pub struct SignUpFormTemplate {
+pub struct SignUpFormTemplate<'a> {
     pub user: Option,
     pub tr: Tr,
 
     pub email: String,
-    pub message: String,
-    pub message_email: String,
-    pub message_password: String,
+    pub message: &'a str,
+    pub message_email: &'a str,
+    pub message_password: &'a str,
 }
 
 #[derive(Template)]
 #[template(path = "sign_in_form.html")]
-pub struct SignInFormTemplate {
+pub struct SignInFormTemplate<'a> {
     pub user: Option,
     pub tr: Tr,
 
-    pub email: String,
-    pub message: String,
+    pub email: &'a str,
+    pub message: &'a str,
 }
 
 #[derive(Template)]
 #[template(path = "ask_reset_password.html")]
-pub struct AskResetPasswordTemplate {
+pub struct AskResetPasswordTemplate<'a> {
     pub user: Option,
     pub tr: Tr,
 
-    pub email: String,
-    pub message: String,
-    pub message_email: String,
+    pub email: &'a str,
+    pub message: &'a str,
+    pub message_email: &'a str,
 }
 
 #[derive(Template)]
 #[template(path = "reset_password.html")]
-pub struct ResetPasswordTemplate {
+pub struct ResetPasswordTemplate<'a> {
     pub user: Option,
     pub tr: Tr,
 
-    pub reset_token: String,
-    pub message: String,
-    pub message_password: String,
+    pub reset_token: &'a str,
+    pub message: &'a str,
+    pub message_password: &'a str,
 }
 
 #[derive(Template)]
 #[template(path = "profile.html")]
-pub struct ProfileTemplate {
+pub struct ProfileTemplate<'a> {
     pub user: Option,
     pub tr: Tr,
 
-    pub username: String,
-    pub email: String,
-    pub message: String,
-    pub message_email: String,
-    pub message_password: String,
+    pub username: &'a str,
+    pub email: &'a str,
+    pub message: &'a str,
+    pub message_email: &'a str,
+    pub message_password: &'a str,
 }
 
 #[derive(Template)]
diff --git a/backend/src/main.rs b/backend/src/main.rs
index 274349a..90b169e 100644
--- a/backend/src/main.rs
+++ b/backend/src/main.rs
@@ -245,7 +245,11 @@ async fn translation(
                     .map(|l| l.split('-').next().unwrap_or_default())
                     .find_or_first(|l| available_codes.contains(l));
 
-                accept_language.unwrap_or("en").to_string()
+                match accept_language {
+                    Some(lang) if !lang.is_empty() => lang,
+                    _ => translation::DEFAULT_LANGUAGE_CODE,
+                }
+                .to_string()
             }
         }
     };
diff --git a/backend/src/services.rs b/backend/src/services/mod.rs
similarity index 95%
rename from backend/src/services.rs
rename to backend/src/services/mod.rs
index 1a18e16..05aed48 100644
--- a/backend/src/services.rs
+++ b/backend/src/services/mod.rs
@@ -33,7 +33,7 @@ pub async fn ron_error_to_html(
             };
             return Ok(MessageTemplate {
                 user: None,
-                message,
+                message: &message,
                 as_code: true,
                 tr,
             }
@@ -78,6 +78,6 @@ pub async fn not_found(
 ) -> impl IntoResponse {
     (
         StatusCode::NOT_FOUND,
-        MessageTemplate::new_with_user("404: Not found".to_string(), tr, user),
+        MessageTemplate::new_with_user("404: Not found", tr, user),
     )
 }
diff --git a/backend/src/services/recipe.rs b/backend/src/services/recipe.rs
index 9887b2d..39d5778 100644
--- a/backend/src/services/recipe.rs
+++ b/backend/src/services/recipe.rs
@@ -79,7 +79,7 @@ pub async fn view(
                 && (user.is_none() || recipe.user_id != user.as_ref().unwrap().id)
             {
                 return Ok(MessageTemplate::new_with_user(
-                    tr.tp(Sentence::RecipeNotAllowedToView, &[Box::new(recipe_id)]),
+                    &tr.tp(Sentence::RecipeNotAllowedToView, &[Box::new(recipe_id)]),
                     tr,
                     user,
                 )
diff --git a/backend/src/services/user.rs b/backend/src/services/user.rs
index ae2b138..e54672e 100644
--- a/backend/src/services/user.rs
+++ b/backend/src/services/user.rs
@@ -34,9 +34,9 @@ pub async fn sign_up_get(
         user,
         tr,
         email: String::new(),
-        message: String::new(),
-        message_email: String::new(),
-        message_password: String::new(),
+        message: "",
+        message_email: "",
+        message_password: "",
     })
 }
 
@@ -71,26 +71,27 @@ pub async fn sign_up_post(
         user: Option,
         tr: translation::Tr,
     ) -> Result {
+        let invalid_password_mess = &tr.tp(
+            Sentence::InvalidPassword,
+            &[Box::new(common::consts::MIN_PASSWORD_SIZE)],
+        );
         Ok(SignUpFormTemplate {
             user,
             email: form_data.email.clone(),
             message_email: match error {
                 SignUpError::InvalidEmail => tr.t(Sentence::InvalidEmail),
-                _ => String::new(),
+                _ => "",
             },
             message_password: match error {
                 SignUpError::PasswordsNotEqual => tr.t(Sentence::PasswordDontMatch),
-                SignUpError::InvalidPassword => tr.tp(
-                    Sentence::InvalidPassword,
-                    &[Box::new(common::consts::MIN_PASSWORD_SIZE)],
-                ),
-                _ => String::new(),
+                SignUpError::InvalidPassword => invalid_password_mess,
+                _ => "",
             },
             message: match error {
                 SignUpError::UserAlreadyExists => tr.t(Sentence::EmailAlreadyTaken),
-                SignUpError::DatabaseError => "Database error".to_string(),
+                SignUpError::DatabaseError => tr.t(Sentence::DatabaseError),
                 SignUpError::UnableSendEmail => tr.t(Sentence::UnableToSendEmail),
-                _ => String::new(),
+                _ => "",
             },
             tr,
         }
@@ -235,8 +236,8 @@ pub async fn sign_in_get(
     Ok(SignInFormTemplate {
         user,
         tr,
-        email: String::new(),
-        message: String::new(),
+        email: "",
+        message: "",
     })
 }
 
@@ -271,7 +272,7 @@ pub async fn sign_in_post(
             jar,
             SignInFormTemplate {
                 user,
-                email: form_data.email,
+                email: &form_data.email,
                 message: tr.t(Sentence::AccountMustBeValidatedFirst),
                 tr,
             }
@@ -281,7 +282,7 @@ pub async fn sign_in_post(
             jar,
             SignInFormTemplate {
                 user,
-                email: form_data.email,
+                email: &form_data.email,
                 message: tr.t(Sentence::WrongEmailOrPassword),
                 tr,
             }
@@ -326,9 +327,9 @@ pub async fn ask_reset_password_get(
         Ok(AskResetPasswordTemplate {
             user,
             tr,
-            email: String::new(),
-            message: String::new(),
-            message_email: String::new(),
+            email: "",
+            message: "",
+            message_email: "",
         }
         .into_response())
     }
@@ -364,10 +365,10 @@ pub async fn ask_reset_password_post(
     ) -> Result {
         Ok(AskResetPasswordTemplate {
             user,
-            email: email.to_string(),
+            email,
             message_email: match error {
                 AskResetPasswordError::InvalidEmail => tr.t(Sentence::InvalidEmail),
-                _ => String::new(),
+                _ => "",
             },
             message: match error {
                 AskResetPasswordError::EmailAlreadyReset => {
@@ -376,7 +377,7 @@ pub async fn ask_reset_password_post(
                 AskResetPasswordError::EmailUnknown => tr.t(Sentence::EmailUnknown),
                 AskResetPasswordError::UnableSendEmail => tr.t(Sentence::UnableToSendResetEmail),
                 AskResetPasswordError::DatabaseError => tr.t(Sentence::DatabaseError),
-                _ => String::new(),
+                _ => "",
             },
             tr,
         }
@@ -470,9 +471,9 @@ pub async fn reset_password_get(
         Ok(ResetPasswordTemplate {
             user,
             tr,
-            reset_token: reset_token.to_string(),
-            message: String::new(),
-            message_password: String::new(),
+            reset_token,
+            message: "",
+            message_password: "",
         }
         .into_response())
     } else {
@@ -510,21 +511,22 @@ pub async fn reset_password_post(
         user: Option,
         tr: translation::Tr,
     ) -> Result {
+        let reset_password_mess = &tr.tp(
+            Sentence::InvalidPassword,
+            &[Box::new(common::consts::MIN_PASSWORD_SIZE)],
+        );
         Ok(ResetPasswordTemplate {
             user,
-            reset_token: form_data.reset_token.clone(),
+            reset_token: &form_data.reset_token,
             message_password: match error {
                 ResetPasswordError::PasswordsNotEqual => tr.t(Sentence::PasswordDontMatch),
-                ResetPasswordError::InvalidPassword => tr.tp(
-                    Sentence::InvalidPassword,
-                    &[Box::new(common::consts::MIN_PASSWORD_SIZE)],
-                ),
-                _ => String::new(),
+                ResetPasswordError::InvalidPassword => reset_password_mess,
+                _ => "",
             },
             message: match error {
                 ResetPasswordError::TokenExpired => tr.t(Sentence::AskResetTokenExpired),
                 ResetPasswordError::DatabaseError => tr.t(Sentence::DatabaseError),
-                _ => String::new(),
+                _ => "",
             },
             tr,
         }
@@ -571,12 +573,12 @@ pub async fn edit_user_get(
 ) -> Response {
     if let Some(user) = user {
         ProfileTemplate {
-            username: user.name.clone(),
-            email: user.email.clone(),
-            message: String::new(),
-            message_email: String::new(),
-            message_password: String::new(),
-            user: Some(user),
+            username: &user.name,
+            email: &user.email,
+            message: "",
+            message_email: "",
+            message_password: "",
+            user: Some(user.clone()),
             tr,
         }
         .into_response()
@@ -592,6 +594,7 @@ pub struct EditUserForm {
     password_1: String,
     password_2: String,
 }
+
 enum ProfileUpdateError {
     InvalidEmail,
     EmailAlreadyTaken,
@@ -618,27 +621,28 @@ pub async fn edit_user_post(
             user: model::User,
             tr: translation::Tr,
         ) -> Result {
+            let invalid_password_mess = &tr.tp(
+                Sentence::InvalidPassword,
+                &[Box::new(common::consts::MIN_PASSWORD_SIZE)],
+            );
             Ok(ProfileTemplate {
                 user: Some(user),
-                username: form_data.name.clone(),
-                email: form_data.email.clone(),
+                username: &form_data.name,
+                email: &form_data.email,
                 message_email: match error {
                     ProfileUpdateError::InvalidEmail => tr.t(Sentence::InvalidEmail),
                     ProfileUpdateError::EmailAlreadyTaken => tr.t(Sentence::EmailAlreadyTaken),
-                    _ => String::new(),
+                    _ => "",
                 },
                 message_password: match error {
                     ProfileUpdateError::PasswordsNotEqual => tr.t(Sentence::PasswordDontMatch),
-                    ProfileUpdateError::InvalidPassword => tr.tp(
-                        Sentence::InvalidPassword,
-                        &[Box::new(common::consts::MIN_PASSWORD_SIZE)],
-                    ),
-                    _ => String::new(),
+                    ProfileUpdateError::InvalidPassword => invalid_password_mess,
+                    _ => "",
                 },
                 message: match error {
                     ProfileUpdateError::DatabaseError => tr.t(Sentence::DatabaseError),
                     ProfileUpdateError::UnableSendEmail => tr.t(Sentence::UnableToSendEmail),
-                    _ => String::new(),
+                    _ => "",
                 },
                 tr,
             }
@@ -666,7 +670,7 @@ pub async fn edit_user_post(
         };
 
         let email_trimmed = form_data.email.trim();
-        let message: String;
+        let message: &str;
 
         match connection
             .update_user(
@@ -725,11 +729,11 @@ pub async fn edit_user_post(
 
         Ok(ProfileTemplate {
             user,
-            username: form_data.name,
-            email: form_data.email,
+            username: &form_data.name,
+            email: &form_data.email,
             message,
-            message_email: String::new(),
-            message_password: String::new(),
+            message_email: "",
+            message_password: "",
             tr,
         }
         .into_response())
diff --git a/backend/src/translation.rs b/backend/src/translation.rs
index aede01d..8cf4489 100644
--- a/backend/src/translation.rs
+++ b/backend/src/translation.rs
@@ -6,7 +6,7 @@ use strum::EnumCount;
 use strum_macros::EnumCount;
 use tracing::{event, Level};
 
-use crate::consts;
+use crate::{consts, utils};
 
 #[derive(Debug, Clone, EnumCount, Deserialize)]
 pub enum Sentence {
@@ -108,7 +108,8 @@ pub enum Sentence {
     RecipeIngredientComment,
 }
 
-const DEFAULT_LANGUAGE_CODE: &str = "en";
+pub const DEFAULT_LANGUAGE_CODE: &str = "en";
+pub const PLACEHOLDER_SUBSTITUTE: &str = "{}";
 
 #[derive(Clone)]
 pub struct Tr {
@@ -122,38 +123,21 @@ impl Tr {
         }
     }
 
-    pub fn t(&self, sentence: Sentence) -> String {
-        //&'static str {
-        self.lang.get(sentence).to_string()
-        // match self.lang.translation.get(&sentence) {
-        //     Some(str) => str.clone(),
-        //     None => format!(
-        //         "Translation missing, lang: {}/{}, element: {:?}",
-        //         self.lang.name, self.lang.code, sentence
-        //     ),
-        // }
+    pub fn t(&self, sentence: Sentence) -> &'static str {
+        self.lang.get(sentence)
     }
 
     pub fn tp(&self, sentence: Sentence, params: &[Box]) -> String {
-        // match self.lang.translation.get(&sentence) {
-        //     Some(str) => {
-        //         let mut result = str.clone();
-        //         for p in params {
-        //             result = result.replacen("{}", &p.to_string(), 1);
-        //         }
-        //         result
-        //     }
-        //     None => format!(
-        //         "Translation missing, lang: {}/{}, element: {:?}",
-        //         self.lang.name, self.lang.code, sentence
-        //     ),
-        // }
         let text = self.lang.get(sentence);
-        let mut result = text.to_string();
-        for p in params {
-            result = result.replacen("{}", &p.to_string(), 1);
-        }
-        result
+        let params_as_string: Vec = params.iter().map(|p| p.to_string()).collect();
+        utils::substitute(
+            text,
+            PLACEHOLDER_SUBSTITUTE,
+            ¶ms_as_string
+                .iter()
+                .map(AsRef::as_ref)
+                .collect::>(),
+        )
     }
 
     pub fn current_lang_code(&self) -> &str {
@@ -191,7 +175,6 @@ struct Language {
 
 impl Language {
     pub fn from_stored_language(stored_language: StoredLanguage) -> Self {
-        println!("!!!!!!!!!!!! {:?}", &stored_language.code);
         Self {
             code: stored_language.code,
             name: stored_language.name,
diff --git a/backend/src/utils.rs b/backend/src/utils.rs
index f8715f3..fddeb71 100644
--- a/backend/src/utils.rs
+++ b/backend/src/utils.rs
@@ -39,3 +39,44 @@ pub fn get_url_from_host(host: &str) -> String {
         host
     )
 }
+
+pub fn substitute(str: &str, pattern: &str, replacements: &[&str]) -> String {
+    let mut result = String::with_capacity(
+        (str.len() + replacements.iter().map(|s| s.len()).sum::())
+            .saturating_sub(pattern.len() * replacements.len()),
+    );
+
+    let mut i = 0;
+    for s in str.split(pattern) {
+        result.push_str(s);
+        if i < replacements.len() {
+            result.push_str(replacements[i]);
+        }
+        i += 1;
+    }
+
+    if i == 1 {
+        return str.to_string();
+    }
+
+    result
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_substitute() {
+        assert_eq!(substitute("", "", &[]), "");
+        assert_eq!(substitute("", "", &[""]), "");
+        assert_eq!(substitute("", "{}", &["a"]), "");
+        assert_eq!(substitute("a", "{}", &["b"]), "a");
+        assert_eq!(substitute("a{}", "{}", &["b"]), "ab");
+        assert_eq!(substitute("{}c", "{}", &["b"]), "bc");
+        assert_eq!(substitute("a{}c", "{}", &["b"]), "abc");
+        assert_eq!(substitute("{}b{}", "{}", &["a", "c"]), "abc");
+        assert_eq!(substitute("{}{}{}", "{}", &["a", "bc", "def"]), "abcdef");
+        assert_eq!(substitute("{}{}{}", "{}", &["a"]), "a");
+    }
+}
diff --git a/frontend/src/handles.rs b/frontend/src/handles.rs
index 56b69ac..d05fa41 100644
--- a/frontend/src/handles.rs
+++ b/frontend/src/handles.rs
@@ -34,7 +34,14 @@ async fn reload_recipes_list(current_recipe_id: i64) {
 pub fn recipe_edit(recipe_id: i64) -> Result<(), JsValue> {
     // Title.
     {
-        let title: HtmlInputElement = by_id("input-title");
+        let Some(title) = document().get_element_by_id("input-title") else {
+            return Err(JsValue::from_str("Unable to find 'input-title' element"));
+        };
+
+        let title: HtmlInputElement = title.dyn_into().unwrap();
+
+        // Check if the recipe has been loaded.
+
         let mut current_title = title.value();
         EventListener::new(&title.clone(), "blur", move |_event| {
             if title.value() != current_title {
diff --git a/frontend/src/lib.rs b/frontend/src/lib.rs
index 93c98b9..eced213 100644
--- a/frontend/src/lib.rs
+++ b/frontend/src/lib.rs
@@ -5,7 +5,7 @@ mod request;
 mod toast;
 mod utils;
 
-use gloo::{events::EventListener, utils::window};
+use gloo::{console::log, events::EventListener, utils::window};
 use utils::by_id;
 use wasm_bindgen::prelude::*;
 use wasm_bindgen_futures::spawn_local;
@@ -22,7 +22,9 @@ pub fn main() -> Result<(), JsValue> {
 
     if let ["recipe", "edit", id] = path[..] {
         let id = id.parse::().unwrap(); // TODO: remove unwrap.
-        handles::recipe_edit(id)?;
+        if let Err(error) = handles::recipe_edit(id) {
+            log!(error);
+        }
 
         // Disable: user editing data are now submitted as classic form data.
         // ["user", "edit"] => {
-- 
2.49.0