Browse Source

Add transaction model methods for retrieving one transaction and the response transaction.

Lee Morgan 1 year ago
parent
commit
89840709f7
2 changed files with 25 additions and 7 deletions
  1. 4 2
      src/controllers/transaction.rs
  2. 21 5
      src/models/transaction.rs

+ 4 - 2
src/controllers/transaction.rs

@@ -1,5 +1,5 @@
 use actix_web::{post, web, HttpResponse, HttpRequest};
-use mongodb::{Database, Collection};
+use mongodb::Database;
 
 use crate::models::transaction::Transaction;
 use crate::app_error::AppError;
@@ -14,5 +14,7 @@ pub async fn create_route(
 ) -> Result<HttpResponse, AppError> {
     let user = user_auth(&db, &request).await?;
     let transaction_collection = db.collection::<Transaction>("transactions");
-    Ok(HttpResponse::Ok().json(user.response(None)))
+    let id = Transaction::insert(&transaction_collection, body.into_inner()).await?;
+    let transaction = Transaction::find_one(&transaction_collection, id).await?;
+    Ok(HttpResponse::Ok().json(transaction.response()))
 }

+ 21 - 5
src/models/transaction.rs

@@ -1,6 +1,6 @@
 use serde::{Serialize, Deserialize};
 use mongodb::Collection;
-use bson::oid::ObjectId;
+use bson::{doc, oid::ObjectId};
 
 use crate::app_error::AppError;
 use crate::dto::transaction::CreateInput;
@@ -26,8 +26,7 @@ impl Transaction {
     pub async fn insert(
         collection: &Collection<Transaction>,
         input: CreateInput,
-        account: ObjectId
-    ) -> Result<(), AppError> {
+    ) -> Result<ObjectId, AppError> {
         let transaction = Transaction {
             id: ObjectId::new(),
             account: ObjectId::parse_str(input.account)?,
@@ -35,7 +34,24 @@ impl Transaction {
             date: input.date
         };
 
-        collection.insert_one(transaction, None).await?;
-        Ok(())
+        let insert_one_result = collection.insert_one(transaction, None).await?;
+        Ok(insert_one_result.inserted_id.as_object_id().unwrap())
+    }
+
+    pub async fn find_one(collection: &Collection<Transaction>, transaction_id: ObjectId) -> Result<Transaction, AppError> {
+        match collection.find_one(doc!{"_id": transaction_id}, None).await {
+            Ok(Some(a)) => Ok(a),
+            Ok(None) => Err(AppError::invalid_input("No transaction with that ID")),
+            Err(e) => Err(AppError::Database(e.into()))
+        }
+    }
+
+    pub fn response(self) -> ResponseTransaction {
+        ResponseTransaction {
+            id: self.id.to_hex(),
+            account: self.account.to_hex(),
+            data: self.data.clone(),
+            date: self.date.clone()
+        }
     }
 }