Refactored API DTOs to be more straight forward.
This commit is contained in:
@@ -4,73 +4,42 @@ use uuid::Uuid;
|
||||
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ScheduledTransactionRequest {
|
||||
Recurring(RecurringTransactionRequest),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ScheduledTransaction {
|
||||
Recurring(RecurringTransaction),
|
||||
pub enum ScheduledTransactionResponse {
|
||||
Recurring(RecurringTransactionResponse),
|
||||
}
|
||||
|
||||
impl From<RecurringTransaction> for ScheduledTransaction {
|
||||
fn from(transaction: RecurringTransaction) -> Self {
|
||||
impl From<RecurringTransactionResponse> for ScheduledTransactionResponse {
|
||||
fn from(transaction: RecurringTransactionResponse) -> Self {
|
||||
Self::Recurring(transaction)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RecurringTransaction {
|
||||
pub id: Uuid,
|
||||
|
||||
#[serde(flatten)]
|
||||
pub data: RecurringTransactionData,
|
||||
|
||||
/// The next scheduled occurrence of the transaction.
|
||||
pub next: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl RecurringTransaction {
|
||||
pub fn new(transaction: domain::RecurringTransaction, next: Option<DateTime<Utc>>) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
next,
|
||||
data: RecurringTransactionData {
|
||||
name: transaction.name,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
start: transaction.schedule.start(),
|
||||
end: transaction.schedule.end(),
|
||||
recurrence: transaction.schedule.recurrence().into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ScheduledTransactionData {
|
||||
Recurring(RecurringTransactionData),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RecurringTransactionData {
|
||||
pub struct RecurringTransactionRequest {
|
||||
pub name: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
pub schedule: ScheduleRequest,
|
||||
}
|
||||
|
||||
impl RecurringTransactionData {
|
||||
impl RecurringTransactionRequest {
|
||||
pub fn into_domain(
|
||||
self,
|
||||
id: Uuid,
|
||||
) -> Result<domain::RecurringTransaction, domain::ValidationError> {
|
||||
let recurrence = domain::Recurrence {
|
||||
every: domain::RecurrenceInterval::try_from(self.recurrence.every)?,
|
||||
unit: self.recurrence.unit.into(),
|
||||
weekend_adjustment: self.recurrence.weekend_adjustment.map(Into::into),
|
||||
every: domain::RecurrenceInterval::try_from(self.schedule.recurrence.every)?,
|
||||
unit: self.schedule.recurrence.unit.into(),
|
||||
};
|
||||
|
||||
Ok(domain::RecurringTransaction {
|
||||
@@ -78,16 +47,70 @@ impl RecurringTransactionData {
|
||||
name: self.name,
|
||||
amount: domain::Cents::try_from(self.amount_cents)?,
|
||||
direction: self.direction.into(),
|
||||
schedule: domain::Schedule::new(self.start, self.end, recurrence)?,
|
||||
schedule: domain::Schedule::new(
|
||||
self.schedule.start,
|
||||
self.schedule.end,
|
||||
recurrence,
|
||||
self.schedule.weekend_adjustment.map(Into::into),
|
||||
)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RecurringTransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub schedule: ScheduleResponse,
|
||||
}
|
||||
|
||||
impl RecurringTransactionResponse {
|
||||
pub fn new(transaction: domain::RecurringTransaction, next: Option<DateTime<Utc>>) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
name: transaction.name,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
schedule: ScheduleResponse::new(transaction.schedule, next),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ScheduleRequest {
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ScheduleResponse {
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
pub next: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl ScheduleResponse {
|
||||
fn new(schedule: domain::Schedule, next: Option<DateTime<Utc>>) -> Self {
|
||||
Self {
|
||||
start: schedule.start(),
|
||||
end: schedule.end(),
|
||||
recurrence: schedule.recurrence().into(),
|
||||
weekend_adjustment: schedule.weekend_adjustment().map(Into::into),
|
||||
next,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Recurrence {
|
||||
pub every: u32,
|
||||
pub unit: RecurrenceUnit,
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
}
|
||||
|
||||
impl From<domain::Recurrence> for Recurrence {
|
||||
@@ -95,7 +118,6 @@ impl From<domain::Recurrence> for Recurrence {
|
||||
Self {
|
||||
every: recurrence.every.get(),
|
||||
unit: recurrence.unit.into(),
|
||||
weekend_adjustment: recurrence.weekend_adjustment.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,53 +184,60 @@ mod tests {
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
Recurrence, RecurrenceUnit, RecurringTransaction, RecurringTransactionData,
|
||||
ScheduledTransaction, ScheduledTransactionData, WeekendAdjustment,
|
||||
Recurrence, RecurrenceUnit, RecurringTransactionRequest, RecurringTransactionResponse,
|
||||
ScheduleRequest, ScheduledTransactionRequest, ScheduledTransactionResponse,
|
||||
WeekendAdjustment,
|
||||
};
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
fn data(amount_cents: u64) -> RecurringTransactionData {
|
||||
RecurringTransactionData {
|
||||
fn request(amount_cents: u64) -> RecurringTransactionRequest {
|
||||
RecurringTransactionRequest {
|
||||
name: String::new(),
|
||||
amount_cents,
|
||||
direction: Direction::Out,
|
||||
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||
end: None,
|
||||
recurrence: Recurrence {
|
||||
every: 2,
|
||||
unit: RecurrenceUnit::Month,
|
||||
schedule: ScheduleRequest {
|
||||
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||
end: None,
|
||||
recurrence: Recurrence {
|
||||
every: 2,
|
||||
unit: RecurrenceUnit::Month,
|
||||
},
|
||||
weekend_adjustment: Some(WeekendAdjustment::NextBusinessDay),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_scheduled_transaction_json_flat() {
|
||||
let transaction = data(1234).into_domain(Uuid::nil()).unwrap();
|
||||
let response = ScheduledTransaction::from(RecurringTransaction::new(transaction, None));
|
||||
fn serializes_scheduled_transaction_with_nested_schedule() {
|
||||
let transaction = request(1234).into_domain(Uuid::nil()).unwrap();
|
||||
let response = ScheduledTransactionResponse::from(RecurringTransactionResponse::new(
|
||||
transaction,
|
||||
None,
|
||||
));
|
||||
|
||||
let response = serde_json::to_value(response).unwrap();
|
||||
assert_eq!(response["type"], "recurring");
|
||||
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||
assert!(response["next"].is_null());
|
||||
assert_eq!(response["amount_cents"], 1234);
|
||||
assert_eq!(response["recurrence"]["unit"], "month");
|
||||
assert_eq!(response["schedule"]["recurrence"]["unit"], "month");
|
||||
assert_eq!(
|
||||
response["recurrence"]["weekend_adjustment"],
|
||||
response["schedule"]["weekend_adjustment"],
|
||||
"next_business_day"
|
||||
);
|
||||
assert!(response["schedule"]["next"].is_null());
|
||||
assert!(response.get("next").is_none());
|
||||
assert!(response.get("data").is_none());
|
||||
|
||||
let request: ScheduledTransactionData = serde_json::from_value(response).unwrap();
|
||||
let ScheduledTransactionData::Recurring(data) = request;
|
||||
assert_eq!(data.amount_cents, 1234);
|
||||
assert_eq!(data.recurrence.every, 2);
|
||||
let request: ScheduledTransactionRequest = serde_json::from_value(response).unwrap();
|
||||
let ScheduledTransactionRequest::Recurring(request) = request;
|
||||
assert_eq!(request.amount_cents, 1234);
|
||||
assert_eq!(request.schedule.recurrence.every, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_to_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let transaction = data(1234).into_domain(id).unwrap();
|
||||
let transaction = request(1234).into_domain(id).unwrap();
|
||||
let recurrence = transaction.schedule.recurrence();
|
||||
|
||||
assert_eq!(transaction.id, id);
|
||||
@@ -217,7 +246,7 @@ mod tests {
|
||||
assert_eq!(recurrence.every.get(), 2);
|
||||
assert_eq!(recurrence.unit, domain::RecurrenceUnit::Month);
|
||||
assert_eq!(
|
||||
recurrence.weekend_adjustment,
|
||||
transaction.schedule.weekend_adjustment(),
|
||||
Some(domain::WeekendAdjustment::NextBusinessDay)
|
||||
);
|
||||
}
|
||||
@@ -225,19 +254,19 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_invalid_requests() {
|
||||
assert!(matches!(
|
||||
data(i64::MAX as u64 + 1).into_domain(Uuid::nil()),
|
||||
request(i64::MAX as u64 + 1).into_domain(Uuid::nil()),
|
||||
Err(domain::ValidationError::Amount(_))
|
||||
));
|
||||
|
||||
let mut every = data(100);
|
||||
every.recurrence.every = 0;
|
||||
let mut every = request(100);
|
||||
every.schedule.recurrence.every = 0;
|
||||
assert!(matches!(
|
||||
every.into_domain(Uuid::nil()),
|
||||
Err(domain::ValidationError::RecurrenceInterval(_))
|
||||
));
|
||||
|
||||
let mut end = data(100);
|
||||
end.end = Some(end.start - TimeDelta::seconds(1));
|
||||
let mut end = request(100);
|
||||
end.schedule.end = Some(end.schedule.start - TimeDelta::seconds(1));
|
||||
assert!(matches!(
|
||||
end.into_domain(Uuid::nil()),
|
||||
Err(domain::ValidationError::EndBeforeStart)
|
||||
|
||||
@@ -4,37 +4,15 @@ use uuid::Uuid;
|
||||
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Transaction {
|
||||
pub id: Uuid,
|
||||
|
||||
#[serde(flatten)]
|
||||
pub data: TransactionData,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TransactionData {
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct TransactionRequest {
|
||||
pub description: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl From<domain::Transaction> for Transaction {
|
||||
fn from(transaction: domain::Transaction) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
data: TransactionData {
|
||||
description: transaction.description,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
date: transaction.date,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TransactionData {
|
||||
impl TransactionRequest {
|
||||
pub fn into_domain(self, id: Uuid) -> Result<domain::Transaction, domain::ValidationError> {
|
||||
Ok(domain::Transaction {
|
||||
id,
|
||||
@@ -46,12 +24,33 @@ impl TransactionData {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl From<domain::Transaction> for TransactionResponse {
|
||||
fn from(transaction: domain::Transaction) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
description: transaction.description,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
date: transaction.date,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn data(amount_cents: u64) -> TransactionData {
|
||||
TransactionData {
|
||||
fn request(amount_cents: u64) -> TransactionRequest {
|
||||
TransactionRequest {
|
||||
description: "Groceries".to_string(),
|
||||
amount_cents,
|
||||
direction: Direction::Out,
|
||||
@@ -62,20 +61,20 @@ mod tests {
|
||||
#[test]
|
||||
fn converts_between_dto_and_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let transaction = data(4250).into_domain(id).unwrap();
|
||||
let transaction = request(4250).into_domain(id).unwrap();
|
||||
assert_eq!(transaction.id, id);
|
||||
assert_eq!(transaction.amount.get(), 4250);
|
||||
assert_eq!(transaction.direction, domain::Direction::Out);
|
||||
|
||||
let response = Transaction::from(transaction);
|
||||
let response = TransactionResponse::from(transaction);
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.data.description, "Groceries");
|
||||
assert_eq!(response.data.amount_cents, 4250);
|
||||
assert_eq!(response.description, "Groceries");
|
||||
assert_eq!(response.amount_cents, 4250);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_amounts_that_do_not_fit_in_database() {
|
||||
let error = data(i64::MAX as u64 + 1)
|
||||
let error = request(i64::MAX as u64 + 1)
|
||||
.into_domain(Uuid::nil())
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
@@ -87,18 +86,21 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn keeps_transaction_json_flat() {
|
||||
let response = Transaction {
|
||||
let response = TransactionResponse {
|
||||
id: Uuid::nil(),
|
||||
data: data(4250),
|
||||
description: "Groceries".to_owned(),
|
||||
amount_cents: 4250,
|
||||
direction: Direction::Out,
|
||||
date: Utc::now(),
|
||||
};
|
||||
|
||||
let response = serde_json::to_value(response).unwrap();
|
||||
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||
assert_eq!(response["amount_cents"], 4250);
|
||||
assert_eq!(response["direction"], "out");
|
||||
assert!(response.get("data").is_none());
|
||||
assert_eq!(response["description"], "Groceries");
|
||||
|
||||
let request: TransactionData = serde_json::from_value(response).unwrap();
|
||||
let request: TransactionRequest = serde_json::from_value(response).unwrap();
|
||||
assert_eq!(request.description, "Groceries");
|
||||
assert_eq!(request.amount_cents, 4250);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::{
|
||||
repository::{Delete, Upsert, recurring_transactions as repository},
|
||||
routes::{
|
||||
dtos::scheduled_transaction::{
|
||||
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
|
||||
RecurringTransactionResponse, ScheduledTransactionRequest, ScheduledTransactionResponse,
|
||||
},
|
||||
extractors::{json::Json, path::Path},
|
||||
},
|
||||
@@ -30,12 +30,12 @@ pub fn create_router() -> axum::Router<PgPool> {
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_scheduled_transactions(
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Vec<ScheduledTransaction>>, AppError> {
|
||||
) -> Result<Json<Vec<ScheduledTransactionResponse>>, AppError> {
|
||||
let now = Utc::now();
|
||||
let transactions = repository::list(&pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|transaction| respond(transaction, now))
|
||||
.map(|transaction| create_response(transaction, now))
|
||||
.collect();
|
||||
|
||||
Ok(Json(transactions))
|
||||
@@ -46,12 +46,12 @@ async fn get_scheduled_transactions(
|
||||
async fn get_scheduled_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<ScheduledTransaction>, AppError> {
|
||||
) -> Result<Json<ScheduledTransactionResponse>, AppError> {
|
||||
let transaction = repository::get(&pool, id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(Json(respond(transaction, Utc::now())))
|
||||
Ok(Json(create_response(transaction, Utc::now())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -59,9 +59,9 @@ async fn get_scheduled_transaction(
|
||||
async fn put_scheduled_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(transaction): Json<ScheduledTransactionData>,
|
||||
) -> Result<(StatusCode, Json<ScheduledTransaction>), AppError> {
|
||||
let ScheduledTransactionData::Recurring(transaction) = transaction;
|
||||
Json(transaction): Json<ScheduledTransactionRequest>,
|
||||
) -> Result<(StatusCode, Json<ScheduledTransactionResponse>), AppError> {
|
||||
let ScheduledTransactionRequest::Recurring(transaction) = transaction;
|
||||
let transaction = transaction.into_domain(id)?;
|
||||
|
||||
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||
@@ -69,7 +69,7 @@ async fn put_scheduled_transaction(
|
||||
Upsert::Updated(transaction) => (StatusCode::OK, transaction),
|
||||
};
|
||||
|
||||
Ok((status, Json(respond(transaction, Utc::now()))))
|
||||
Ok((status, Json(create_response(transaction, Utc::now()))))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -84,8 +84,11 @@ async fn delete_scheduled_transaction(
|
||||
}
|
||||
}
|
||||
|
||||
fn respond(transaction: domain::RecurringTransaction, now: DateTime<Utc>) -> ScheduledTransaction {
|
||||
fn create_response(
|
||||
transaction: domain::RecurringTransaction,
|
||||
now: DateTime<Utc>,
|
||||
) -> ScheduledTransactionResponse {
|
||||
let next = transaction.schedule.next_occurrence(now);
|
||||
|
||||
RecurringTransaction::new(transaction, next).into()
|
||||
RecurringTransactionResponse::new(transaction, next).into()
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::{
|
||||
error::AppError,
|
||||
repository::{Delete, Upsert, transactions as repository},
|
||||
routes::{
|
||||
dtos::transaction::{Transaction, TransactionData},
|
||||
dtos::transaction::{TransactionRequest, TransactionResponse},
|
||||
extractors::{json::Json, path::Path},
|
||||
},
|
||||
};
|
||||
@@ -24,11 +24,13 @@ pub fn create_router() -> axum::Router<PgPool> {
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_transactions(State(pool): State<PgPool>) -> Result<Json<Vec<Transaction>>, AppError> {
|
||||
async fn get_transactions(
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Vec<TransactionResponse>>, AppError> {
|
||||
let transactions = repository::list(&pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(Transaction::from)
|
||||
.map(TransactionResponse::from)
|
||||
.collect();
|
||||
|
||||
Ok(Json(transactions))
|
||||
@@ -39,7 +41,7 @@ async fn get_transactions(State(pool): State<PgPool>) -> Result<Json<Vec<Transac
|
||||
async fn get_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<Transaction>, AppError> {
|
||||
) -> Result<Json<TransactionResponse>, AppError> {
|
||||
let transaction = repository::get(&pool, id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
@@ -52,8 +54,8 @@ async fn get_transaction(
|
||||
async fn put_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(transaction): Json<TransactionData>,
|
||||
) -> Result<(StatusCode, Json<Transaction>), AppError> {
|
||||
Json(transaction): Json<TransactionRequest>,
|
||||
) -> Result<(StatusCode, Json<TransactionResponse>), AppError> {
|
||||
let transaction = transaction.into_domain(id)?;
|
||||
|
||||
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||
|
||||
Reference in New Issue
Block a user