Added accounts API.

This commit is contained in:
2026-09-27 10:26:11 +02:00
parent 5f4c9bdf90
commit 4e1eea5849
18 changed files with 540 additions and 0 deletions
+119
View File
@@ -0,0 +1,119 @@
use uuid::Uuid;
use super::{
DecodeError, QueryConversionError, RepositoryError,
dtos::{Delete, Upsert},
};
use crate::{
database::{accounts as db, dtos::AccountRow},
domain::Account,
};
pub struct Query {
pub limit: Option<u64>,
pub offset: Option<u64>,
}
impl TryFrom<Query> for db::Query {
type Error = QueryConversionError;
fn try_from(query: Query) -> Result<Self, Self::Error> {
Ok(db::Query {
limit: query
.limit
.map(|l| i64::try_from(l).map_err(|_| QueryConversionError::Limit(l)))
.transpose()?,
offset: query
.offset
.map(|o| i64::try_from(o).map_err(|_| QueryConversionError::Offset(o)))
.transpose()?,
})
}
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<Account>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let accounts = db::query(executor, query.try_into()?)
.await?
.into_iter()
.map(decode)
.collect::<Result<_, DecodeError>>()?;
Ok(accounts)
}
pub async fn get<'e, E>(executor: E, id: Uuid) -> Result<Option<Account>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let account = db::get_by_id(executor, id).await?.map(decode).transpose()?;
Ok(account)
}
pub async fn upsert<'e, E>(
executor: E,
account: Account,
) -> Result<Upsert<Account>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let account = db::upsert(executor, encode(account))
.await?
.try_map(decode)?;
Ok(account.into())
}
pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result<Delete, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::delete_by_id(executor, id).await?.into())
}
fn decode(row: AccountRow) -> Result<Account, DecodeError> {
Ok(Account {
id: row.id,
name: row.name,
})
}
fn encode(account: Account) -> AccountRow {
AccountRow {
id: account.id,
name: account.name,
}
}
#[cfg(test)]
mod tests {
use uuid::Uuid;
use super::*;
fn row() -> AccountRow {
AccountRow {
id: Uuid::new_v4(),
name: "Savings".to_owned(),
}
}
#[test]
fn decodes_valid_rows() {
let row = row();
let id = row.id;
let account = decode(row).unwrap();
assert_eq!(account.id, id);
assert_eq!(account.name, "Savings");
}
#[test]
fn round_trips_through_rows() {
let account = decode(row()).unwrap();
assert_eq!(decode(encode(account.clone())).unwrap(), account);
}
}