Added accounts API.
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
pub mod accounts;
|
||||
pub mod dtos;
|
||||
pub mod recurring_transactions;
|
||||
pub mod transactions;
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::dtos::{AccountRow, Delete, Upsert};
|
||||
|
||||
pub struct Query {
|
||||
pub limit: Option<i64>,
|
||||
pub offset: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn query<'e, E>(executor: E, query: Query) -> Result<Vec<AccountRow>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query_as!(
|
||||
AccountRow,
|
||||
r#"
|
||||
SELECT id, name
|
||||
FROM accounts
|
||||
ORDER BY name DESC, id DESC
|
||||
LIMIT $1
|
||||
OFFSET $2
|
||||
"#,
|
||||
query.limit,
|
||||
query.offset,
|
||||
)
|
||||
.fetch_all(executor)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<AccountRow>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query_as!(
|
||||
AccountRow,
|
||||
r#"
|
||||
SELECT id, name
|
||||
FROM accounts
|
||||
WHERE id = $1
|
||||
"#,
|
||||
id,
|
||||
)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(
|
||||
executor: E,
|
||||
account: AccountRow,
|
||||
) -> Result<Upsert<AccountRow>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let row = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO accounts (id, name)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
name = EXCLUDED.name
|
||||
RETURNING WITH (OLD AS old_row, NEW AS new_row)
|
||||
old_row.id AS "old_id?",
|
||||
new_row.id AS "id!",
|
||||
new_row.name AS "name!"
|
||||
"#,
|
||||
account.id,
|
||||
account.name,
|
||||
)
|
||||
.fetch_one(executor)
|
||||
.await?;
|
||||
|
||||
let account = AccountRow {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
};
|
||||
|
||||
if row.old_id.is_some() {
|
||||
Ok(Upsert::Updated(account))
|
||||
} else {
|
||||
Ok(Upsert::Created(account))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Delete, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let deleted = sqlx::query!("DELETE FROM accounts WHERE id = $1 RETURNING id", id)
|
||||
.fetch_optional(executor)
|
||||
.await?;
|
||||
|
||||
Ok(if deleted.is_some() {
|
||||
Delete::Deleted
|
||||
} else {
|
||||
Delete::NotFound
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
mod account;
|
||||
mod recurring_transaction;
|
||||
mod results;
|
||||
mod transaction;
|
||||
|
||||
pub use account::*;
|
||||
pub use recurring_transaction::*;
|
||||
pub use results::*;
|
||||
pub use transaction::*;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct AccountRow {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
mod account;
|
||||
mod cents;
|
||||
mod direction;
|
||||
mod recurring_transaction;
|
||||
mod schedule;
|
||||
mod transaction;
|
||||
|
||||
pub use account::*;
|
||||
pub use cents::*;
|
||||
pub use direction::*;
|
||||
pub use recurring_transaction::*;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Account {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::domain::{CentsError, ScheduleError};
|
||||
|
||||
pub mod accounts;
|
||||
pub mod dtos;
|
||||
mod encoding;
|
||||
pub mod recurring_transactions;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,19 @@ use axum::{http::StatusCode, routing::get};
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
pub mod accounts;
|
||||
pub mod dtos;
|
||||
pub mod extractors;
|
||||
pub mod scheduled_transactions;
|
||||
pub mod transactions;
|
||||
|
||||
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||
let accounts = accounts::create_router();
|
||||
let scheduled_transactions = scheduled_transactions::create_router();
|
||||
let transactions = transactions::create_router();
|
||||
|
||||
let api = axum::Router::new()
|
||||
.nest("/accounts", accounts)
|
||||
.nest("/scheduled-transactions", scheduled_transactions)
|
||||
.nest("/transactions", transactions);
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
dtos::{AccountRequest, AccountResponse},
|
||||
extractors::{json::Json, path::Path, query::Query},
|
||||
};
|
||||
use crate::{
|
||||
error::AppError,
|
||||
repository::{
|
||||
accounts as repository,
|
||||
dtos::{Delete, Upsert},
|
||||
},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new()
|
||||
.route("/", axum::routing::get(query_accounts))
|
||||
.route(
|
||||
"/{id}",
|
||||
axum::routing::get(get_account)
|
||||
.put(upsert_account)
|
||||
.delete(delete_account),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct QueryParams {
|
||||
pub limit: Option<u64>,
|
||||
pub offset: Option<u64>,
|
||||
}
|
||||
|
||||
impl TryFrom<QueryParams> for repository::Query {
|
||||
type Error = AppError;
|
||||
|
||||
fn try_from(query: QueryParams) -> Result<Self, Self::Error> {
|
||||
Ok(repository::Query {
|
||||
limit: Some(query.limit.unwrap_or(20)),
|
||||
offset: query.offset,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn query_accounts(
|
||||
State(pool): State<PgPool>,
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<AccountResponse>>, AppError> {
|
||||
let accounts = repository::list(&pool, query.try_into()?)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(AccountResponse::from)
|
||||
.collect();
|
||||
|
||||
Ok(Json(accounts))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_account(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<AccountResponse>, AppError> {
|
||||
let account = repository::get(&pool, id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(Json(account.into()))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool, account))]
|
||||
async fn upsert_account(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(account): Json<AccountRequest>,
|
||||
) -> Result<(StatusCode, Json<AccountResponse>), AppError> {
|
||||
let account = account.into_domain(id)?;
|
||||
|
||||
let (status, account) = match repository::upsert(&pool, account).await? {
|
||||
Upsert::Created(account) => (StatusCode::CREATED, account),
|
||||
Upsert::Updated(account) => (StatusCode::OK, account),
|
||||
};
|
||||
|
||||
Ok((status, Json(account.into())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn delete_account(
|
||||
Path(id): Path<Uuid>,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match repository::delete(&pool, id).await? {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
mod account;
|
||||
mod direction;
|
||||
mod scheduled_transaction;
|
||||
mod transaction;
|
||||
|
||||
pub use account::*;
|
||||
pub use direction::*;
|
||||
pub use scheduled_transaction::*;
|
||||
pub use transaction::*;
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct AccountRequest {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl AccountRequest {
|
||||
pub fn into_domain(self, id: Uuid) -> Result<domain::Account, domain::DomainError> {
|
||||
Ok(domain::Account {
|
||||
id,
|
||||
name: self.name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AccountResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl From<domain::Account> for AccountResponse {
|
||||
fn from(account: domain::Account) -> Self {
|
||||
Self {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request() -> AccountRequest {
|
||||
AccountRequest {
|
||||
name: "Savings".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_between_dto_and_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let account = request().into_domain(id).unwrap();
|
||||
assert_eq!(account.id, id);
|
||||
assert_eq!(account.name, "Savings");
|
||||
|
||||
let response = AccountResponse::from(account);
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.name, "Savings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_account_json_flat() {
|
||||
let response = AccountResponse {
|
||||
id: Uuid::nil(),
|
||||
name: "Savings".to_owned(),
|
||||
};
|
||||
|
||||
let response = serde_json::to_value(response).unwrap();
|
||||
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||
assert_eq!(response["name"], "Savings");
|
||||
|
||||
let request: AccountRequest = serde_json::from_value(response).unwrap();
|
||||
assert_eq!(request.name, "Savings");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user