account.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use serde::{Serialize, Deserialize};
  2. use bson::{oid::ObjectId, DateTime, Bson, doc};
  3. use mongodb::Collection;
  4. use futures::stream::TryStreamExt;
  5. use crate::app_error::AppError;
  6. use crate::dto::account::CreateInput;
  7. use crate::models::user::User;
  8. #[derive(Serialize, Deserialize)]
  9. pub struct Account {
  10. #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
  11. pub _id: Option<ObjectId>,
  12. pub user: ObjectId,
  13. pub data: String,
  14. pub created_at: DateTime
  15. }
  16. #[derive(Serialize, Deserialize)]
  17. pub struct ResponseAccount {
  18. pub id: String,
  19. pub data: String,
  20. pub created_at: i64
  21. }
  22. impl Account {
  23. pub async fn insert(collection: &Collection<Account>, input: CreateInput, user: User) -> Result<ObjectId, AppError> {
  24. let object_id = match user._id {
  25. Some(oid) => Ok(oid),
  26. None => Err(AppError::Auth)
  27. };
  28. let account = Account {
  29. _id: None,
  30. user: object_id?,
  31. data: input.data,
  32. created_at: DateTime::now()
  33. };
  34. let result = collection
  35. .insert_one(account, None)
  36. .await?;
  37. match result.inserted_id {
  38. Bson::ObjectId(oid) => Ok(oid),
  39. _ => Err(AppError::InternalError("Invalid Data".to_string()))
  40. }
  41. }
  42. pub async fn find_by_user(collection: &Collection<Account>, user_id: ObjectId) -> Result<Vec<Account>, AppError> {
  43. Ok(collection
  44. .find(doc!{"_id": user_id}, None)
  45. .await?
  46. .try_collect::<Vec<_>>()
  47. .await?)
  48. }
  49. pub async fn find_by_id(collection: &Collection<Account>, account_id: ObjectId) -> Result<Account, AppError> {
  50. match collection.find_one(doc!{"_id": account_id}, None).await {
  51. Ok(Some(a)) => Ok(a),
  52. Ok(None) => Err(AppError::invalid_input("No account with that ID")),
  53. Err(e) => Err(AppError::Database(e.into()))
  54. }
  55. }
  56. pub fn response(self) -> ResponseAccount {
  57. ResponseAccount {
  58. id: self._id.unwrap().to_string(),
  59. data: self.data.clone(),
  60. created_at: self.created_at.timestamp_millis()
  61. }
  62. }
  63. }