Add first routes for accounts management

This commit is contained in:
2025-04-03 23:14:55 +02:00
parent 03f57a0ad7
commit 72e67d9e91
14 changed files with 202 additions and 43 deletions

View File

@@ -0,0 +1,64 @@
use crate::connections::db_connection::db;
use crate::models::accounts::{Account, AccountID, NewAccount};
use crate::models::users::UserID;
use crate::schema::accounts;
use crate::utils::time_utils::time;
use diesel::RunQueryDsl;
use diesel::prelude::*;
#[derive(serde::Deserialize)]
pub struct UpdateAccountQuery {
pub name: String,
}
/// Create a new account
pub async fn create(user_id: UserID, query: &UpdateAccountQuery) -> anyhow::Result<Account> {
let new_account = NewAccount {
name: query.name.as_str(),
user_id: user_id.0,
time_create: time() as i64,
time_update: time() as i64,
};
let res: Account = diesel::insert_into(accounts::table)
.values(&new_account)
.get_result(&mut db()?)?;
update(res.id(), query).await?;
Ok(res)
}
/// Update an account
pub async fn update(id: AccountID, q: &UpdateAccountQuery) -> anyhow::Result<()> {
diesel::update(accounts::dsl::accounts.filter(accounts::dsl::id.eq(id.0)))
.set((
accounts::dsl::time_update.eq(time() as i64),
accounts::dsl::name.eq(&q.name),
))
.execute(&mut db()?)?;
Ok(())
}
/// Get a single account by its id
pub async fn get_by_id(account_id: AccountID) -> anyhow::Result<Account> {
Ok(accounts::table
.filter(accounts::dsl::id.eq(account_id.0))
.get_result(&mut db()?)?)
}
/// Get the accounts of a user
pub async fn get_list_user(id: UserID) -> anyhow::Result<Vec<Account>> {
Ok(accounts::table
.filter(accounts::dsl::user_id.eq(id.0))
.get_results(&mut db()?)?)
}
/// Delete an account
pub async fn delete(id: AccountID) -> anyhow::Result<()> {
diesel::delete(accounts::dsl::accounts.filter(accounts::dsl::id.eq(id.0)))
.execute(&mut db()?)?;
Ok(())
}