diff options
| author | Joe Carstairs <me@joeac.net> | 2024-08-31 22:43:00 +0100 |
|---|---|---|
| committer | Joe Carstairs <me@joeac.net> | 2024-08-31 22:43:00 +0100 |
| commit | 95d4db4da725b74999524a1307e5e17b434dbfeb (patch) | |
| tree | e083d4d12014e78c9e2ba4414ac3cea2fe2563ff /backend/src/routes | |
Backend
Diffstat (limited to 'backend/src/routes')
| -rw-r--r-- | backend/src/routes/account.rs | 68 | ||||
| -rw-r--r-- | backend/src/routes/mod.rs | 1 |
2 files changed, 69 insertions, 0 deletions
diff --git a/backend/src/routes/account.rs b/backend/src/routes/account.rs new file mode 100644 index 0000000..e7f000c --- /dev/null +++ b/backend/src/routes/account.rs @@ -0,0 +1,68 @@ +use diesel::prelude::*; +use diesel::result::DatabaseErrorKind; +use rocket::error::ErrorKind; +use rocket::serde::json::Json; +use rocket::tokio::sync::oneshot::error::RecvError; +use rocket::{get, post, Responder}; + +use crate::databases::UserDataDb; +use crate::models::account::Account; +use crate::schema::accounts::dsl::accounts; + +#[get("/account")] +pub async fn get_all_accounts(user_data_db: UserDataDb) -> Json<Vec<Account>> { + user_data_db + .run(|connection| { + Json( + accounts + .select(Account::as_select()) + .load(connection) + .expect("Error getting accounts"), + ) + }) + .await +} + +#[derive(Responder)] +pub enum CreateAccountResponder { + #[response(status = 500, content_type = "text")] + InternalServerError(String), + + #[response(status = 202, content_type = "json")] + Created(Json<Account>), + + #[response(status = 400, content_type = "text")] + BadRequest(String), +} + +#[post("/account", data = "<account>", format = "json")] +pub async fn create_account( + account: Json<Account>, + user_data_db: UserDataDb, +) -> CreateAccountResponder { + let account = account.into_inner(); + let account_clone = account.clone(); + + let num_rows_inserted = user_data_db + .run(|connection| { + diesel::insert_into(accounts) + .values(vec![account_clone]) + .execute(connection) + }) + .await; + + match num_rows_inserted { + Ok(_) => CreateAccountResponder::Created(Json(account)), + Err(err) => match err { + diesel::result::Error::DatabaseError(DatabaseErrorKind::UniqueViolation, info) => { + let column = info.column_name().unwrap_or("account"); + CreateAccountResponder::BadRequest(format!( + "Error creating account: {column} was not unique." + )) + } + _ => CreateAccountResponder::InternalServerError(format!( + "Error creating account: {err}" + )), + }, + } +} diff --git a/backend/src/routes/mod.rs b/backend/src/routes/mod.rs new file mode 100644 index 0000000..b0edc6c --- /dev/null +++ b/backend/src/routes/mod.rs @@ -0,0 +1 @@ +pub mod account; |
