Added Postgres backend and SQLx.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
pub mod transaction;
|
||||
@@ -0,0 +1,46 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::dtos::transaction::TransactionRow;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct TransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub amount: f64,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl From<TransactionRow> for TransactionResponse {
|
||||
fn from(row: TransactionRow) -> Self {
|
||||
Self {
|
||||
id: row.id,
|
||||
description: row.description,
|
||||
amount: row.amount_cents as f64 / 100.0,
|
||||
date: row.date,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn converts_cents_to_major_currency_units() {
|
||||
let id = Uuid::new_v4();
|
||||
let date = Utc::now();
|
||||
let response = TransactionResponse::from(TransactionRow {
|
||||
id,
|
||||
description: "Groceries".to_string(),
|
||||
amount_cents: 4250,
|
||||
date,
|
||||
});
|
||||
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.description, "Groceries");
|
||||
assert_eq!(response.amount, 42.5);
|
||||
assert_eq!(response.date, date);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,31 @@
|
||||
use crate::models::transaction::Transaction;
|
||||
use axum::{Json, extract::State};
|
||||
use sqlx::PgPool;
|
||||
|
||||
pub fn create_router() -> axum::Router {
|
||||
use crate::{
|
||||
database::dtos::transaction::TransactionRow, error::AppError,
|
||||
routes::dtos::transaction::TransactionResponse,
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new().route("/", axum::routing::get(get_transactions))
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
pub async fn get_transactions() -> axum::Json<Vec<Transaction>> {
|
||||
axum::Json(vec![
|
||||
Transaction {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
description: "Groceries".to_string(),
|
||||
amount: 42.50,
|
||||
date: chrono::Utc::now(),
|
||||
},
|
||||
Transaction {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
description: "Coffee".to_string(),
|
||||
amount: 4.25,
|
||||
date: chrono::Utc::now(),
|
||||
},
|
||||
])
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_transactions(
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Vec<TransactionResponse>>, AppError> {
|
||||
let rows = sqlx::query_as!(
|
||||
TransactionRow,
|
||||
r#"
|
||||
SELECT id, description, amount_cents, date
|
||||
FROM transactions
|
||||
ORDER BY date DESC, id DESC
|
||||
"#
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(
|
||||
rows.into_iter().map(TransactionResponse::from).collect(),
|
||||
))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user