Skip to content

Commit

Permalink
feat(models): move create/update into models
Browse files Browse the repository at this point in the history
  • Loading branch information
corybuecker committed Nov 3, 2024
1 parent b35ebf8 commit 73a53be
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 62 deletions.
14 changes: 4 additions & 10 deletions src/authenticated/envelopes/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use axum::{
Extension, Form,
};
use bson::oid::ObjectId;
use mongodb::Collection;
use std::str::FromStr;
use tera::Context;
use validator::Validate;
Expand Down Expand Up @@ -58,19 +57,14 @@ pub async fn page(
}
}

let goal_record = Envelope {
let envelope = Envelope {
_id: ObjectId::new().to_string(),
name: form.name.to_owned(),
amount: form.amount.to_owned(),
user_id: ObjectId::from_str(&user.id).unwrap().to_string(),
};
let goals: Collection<Envelope> = shared_state
.mongo
.default_database()
.unwrap()
.collection("envelopes");

let _ = goals.insert_one(goal_record).await?;
envelope.create(&shared_state.mongo).await?;

Ok(Redirect::to("/envelopes").into_response())
}
Expand All @@ -84,8 +78,8 @@ mod tests {
use axum::routing::post;
use axum::Router;
use bson::doc;

use mongodb::Collection;

use std::str::from_utf8;
use tower::ServiceExt;

Expand Down
27 changes: 7 additions & 20 deletions src/authenticated/envelopes/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use axum::{
response::{Html, IntoResponse, Redirect, Response},
Extension, Form,
};
use bson::{doc, oid::ObjectId};
use bson::oid::ObjectId;
use std::str::FromStr;
use tera::Context;
use validator::Validate;
Expand Down Expand Up @@ -63,27 +63,14 @@ pub async fn action(
}
}

let envelopes: mongodb::Collection<Envelope> = shared_state
.mongo
.default_database()
.unwrap()
.collection("envelopes");

let filter = doc! {"_id": ObjectId::from_str(&id).unwrap(), "user_id": ObjectId::from_str(&user.id).unwrap()};
log::debug!("{:?}", filter);

let envelope = envelopes.find_one(filter.clone()).await?;

let Some(mut envelope) = envelope else {
return Err(FormError {
message: "could not update envelope".to_string(),
status_code: Some(StatusCode::NOT_FOUND),
});
let envelope = Envelope {
_id: ObjectId::from_str(&id)?.to_string(),
name: form.name.to_owned(),
amount: form.amount.to_owned(),
user_id: ObjectId::from_str(&user.id).unwrap().to_string(),
};

envelope.name = form.name.clone();
envelope.amount = form.amount;
let _ = envelopes.replace_one(filter, envelope).await;
envelope.update(&shared_state.mongo).await?;

Ok(Redirect::to("/envelopes").into_response())
}
Expand Down
10 changes: 2 additions & 8 deletions src/authenticated/goals/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use axum::{
};
use bson::oid::ObjectId;
use chrono::{NaiveDateTime, NaiveTime};
use mongodb::Collection;
use std::str::FromStr;
use tera::Context;
use validator::Validate;
Expand Down Expand Up @@ -77,13 +76,7 @@ pub async fn page(
user_id: ObjectId::from_str(&user.id).unwrap().to_string(),
};

let goals: Collection<Goal> = shared_state
.mongo
.default_database()
.unwrap()
.collection("goals");

let _ = goals.insert_one(goal_record).await?;
goal_record.create(&shared_state.mongo).await?;

Ok(Redirect::to("/goals").into_response())
}
Expand All @@ -98,6 +91,7 @@ mod tests {
use axum::Router;
use bson::doc;
use chrono::{Duration, Utc};
use mongodb::Collection;
use std::ops::Add;
use std::str::from_utf8;
use tower::ServiceExt;
Expand Down
31 changes: 9 additions & 22 deletions src/authenticated/goals/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use axum::{
response::{Html, IntoResponse, Redirect, Response},
Extension, Form,
};
use bson::{doc, oid::ObjectId};
use bson::oid::ObjectId;
use chrono::{NaiveDateTime, NaiveTime};
use std::str::FromStr;
use tera::Context;
Expand Down Expand Up @@ -65,29 +65,16 @@ pub async fn action(
}
}

let goals: mongodb::Collection<Goal> = shared_state
.mongo
.default_database()
.unwrap()
.collection("goals");

let filter = doc! {"_id": ObjectId::from_str(&id).unwrap(), "user_id": ObjectId::from_str(&user.id).unwrap()};
log::debug!("{:?}", filter);

let goal = goals.find_one(filter.clone()).await?;

let Some(mut goal) = goal else {
return Err(FormError {
message: "could not find goal".to_string(),
status_code: Some(StatusCode::NOT_FOUND),
});
let goal_record = Goal {
_id: ObjectId::from_str(&id)?.to_string(),
name: form.name.to_owned(),
target: form.target.to_owned(),
recurrence: Recurrence::from_str(&form.recurrence).unwrap(),
target_date: NaiveDateTime::new(form.target_date, NaiveTime::MIN).and_utc(),
user_id: ObjectId::from_str(&user.id)?.to_string(),
};

goal.name = form.name.clone();
goal.target = form.target;
goal.target_date = NaiveDateTime::new(form.target_date, NaiveTime::MIN).and_utc();
goal.recurrence = Recurrence::from_str(&form.recurrence).unwrap();
let _ = goals.replace_one(filter, goal).await?;
goal_record.update(&shared_state.mongo).await?;

Ok(Redirect::to("/goals").into_response())
}
Expand Down
6 changes: 4 additions & 2 deletions src/models/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,15 @@ impl Account {
.insert_one(self)
.await?)
}

pub async fn update(&self, client: &mongodb::Client) -> Result<UpdateResult, ModelError> {
Ok(client
.default_database()
.ok_or_else(|| ModelError::MissingDefaultDatabase)?
.collection::<Account>("accounts")
.update_one(
.replace_one(
doc! {"_id": ObjectId::parse_str(&self._id)?, "user_id": ObjectId::parse_str(&self.user_id)?},
doc! {"$set": doc! {"name": &self.name, "amount": &self.amount, "debt": &self.debt}},
self
)
.await?)
}
Expand Down Expand Up @@ -71,6 +72,7 @@ impl Account {
.map(|e| e.amount)
.reduce(|memo, amount| memo + amount)
.unwrap_or(0.0);

let non_debt = accounts
.iter()
.filter(|a| !a.debt)
Expand Down
27 changes: 27 additions & 0 deletions src/models/envelope.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
use bson::doc;
use bson::oid::ObjectId;
use bson::serde_helpers::hex_string_as_object_id;
use mongodb::results::InsertOneResult;
use mongodb::results::UpdateResult;
use mongodb::Collection;
use serde::Deserialize;
use serde::Serialize;

use crate::errors::ModelError;

#[derive(Deserialize, Serialize, Debug)]
pub struct Envelope {
#[serde(with = "hex_string_as_object_id")]
Expand All @@ -17,6 +21,29 @@ pub struct Envelope {
pub amount: f64,
}

impl Envelope {
pub async fn create(&self, client: &mongodb::Client) -> Result<InsertOneResult, ModelError> {
Ok(client
.default_database()
.ok_or_else(|| ModelError::MissingDefaultDatabase)?
.collection::<Envelope>("envelopes")
.insert_one(self)
.await?)
}

pub async fn update(&self, client: &mongodb::Client) -> Result<UpdateResult, ModelError> {
Ok(client
.default_database()
.ok_or_else(|| ModelError::MissingDefaultDatabase)?
.collection::<Envelope>("envelopes")
.replace_one(
doc! {"_id": ObjectId::parse_str(&self._id)?, "user_id": ObjectId::parse_str(&self.user_id)?},
self
)
.await?)
}
}

pub async fn envelopes_total_for(user_id: &ObjectId, client: &mongodb::Client) -> f64 {
let collection: Collection<Envelope> =
client.default_database().unwrap().collection("envelopes");
Expand Down
22 changes: 22 additions & 0 deletions src/models/goal.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::errors::ModelError;
use bson::{doc, oid::ObjectId, serde_helpers::hex_string_as_object_id};
use chrono::{DateTime, Datelike, Days, Duration, Local, Months, TimeDelta, Timelike, Utc};
use mongodb::results::{InsertOneResult, UpdateResult};
use serde::{Deserialize, Serialize};
use std::ops::Add;

Expand Down Expand Up @@ -52,6 +53,27 @@ pub struct Goal {
}

impl Goal {
pub async fn create(&self, client: &mongodb::Client) -> Result<InsertOneResult, ModelError> {
Ok(client
.default_database()
.ok_or_else(|| ModelError::MissingDefaultDatabase)?
.collection::<Goal>("goals")
.insert_one(self)
.await?)
}

pub async fn update(&self, client: &mongodb::Client) -> Result<UpdateResult, ModelError> {
Ok(client
.default_database()
.ok_or_else(|| ModelError::MissingDefaultDatabase)?
.collection::<Goal>("goals")
.replace_one(
doc! {"_id": ObjectId::parse_str(&self._id)?, "user_id": ObjectId::parse_str(&self.user_id)?},
self
)
.await?)
}

pub async fn get_by_user_id(
client: &mongodb::Client,
user_id: &str,
Expand Down

0 comments on commit 73a53be

Please sign in to comment.