Skip to content

Commit 1648e75

Browse files
author
David Silva
committed
delete and update refactor
1 parent 8fad292 commit 1648e75

File tree

2 files changed

+60
-41
lines changed

2 files changed

+60
-41
lines changed

src/articles/model.rs

Lines changed: 52 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,26 @@ pub mod article {
3030
pub content: String,
3131
pub created_at: String,
3232
}
33-
33+
34+
// @todo -> How to unify struct ArticleRequest with ArticleUpdateRequest | If possible unify with ArticleModel, why not?
35+
#[derive(Serialize, Deserialize)]
36+
pub struct ArticleRequest {
37+
pub author: String,
38+
pub title: String,
39+
pub content: String,
40+
pub created_at: String,
41+
}
42+
43+
#[derive(Serialize, Deserialize)]
44+
pub struct ArticleUpdateRequest {
45+
#[serde(rename = "_id")]
46+
pub _id: String,
47+
pub author: String,
48+
pub title: String,
49+
pub content: String,
50+
pub created_at: String,
51+
}
52+
3453
pub async fn _all() -> Result<Vec<ArticleModel>> {
3554
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");
3655
let db = Client::with_uri_str(&database_url).await?.database(MONGO_DB);
@@ -57,17 +76,7 @@ pub mod article {
5776

5877
Ok(doc)
5978
}
60-
61-
62-
// @todo -> How to unify struct ArticleRequest with ArticleUpdateRequest
63-
#[derive(Serialize, Deserialize)]
64-
pub struct ArticleRequest {
65-
pub author: String,
66-
pub title: String,
67-
pub content: String,
68-
pub created_at: String,
69-
}
70-
79+
7180
pub async fn _create(_article: web::Json<ArticleRequest>) -> Result<ArticleModel> {
7281
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");
7382
let db = Client::with_uri_str(&database_url).await?.database(MONGO_DB);
@@ -85,25 +94,47 @@ pub mod article {
8594
Ok(to_save)
8695
}
8796

88-
pub async fn _update(_article: bson::Document, query: bson::Document) -> Result<Option<ArticleModel>> {
97+
pub async fn _update(_article: web::Json<ArticleUpdateRequest>) -> Result<()> {
8998
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");
9099
let db = Client::with_uri_str(&database_url).await?.database(MONGO_DB);
91100

92-
let doc = ArticleModel::find_one(&db, query, None).await?;
93-
println!("{:?}", doc);
101+
// This is bad code, how to dont pass all params? -> need improve
102+
let to_update = ArticleModel {
103+
id: serde::__private::Some(ObjectId::with_string(&_article._id.clone()).unwrap()), // bad code
104+
author: _article.author.clone(),
105+
created_at: _article.created_at.clone(),
106+
title: _article.title.clone(),
107+
content: _article.content.clone(),
108+
};
109+
110+
let document = doc! {
111+
"author": _article.author.clone(),
112+
"created_at": _article.created_at.clone(),
113+
"title": _article.title.clone(),
114+
"content": _article.content.clone(),
115+
};
116+
117+
to_update.update(&db, None, doc!{"$set": document}, None).await?;
94118

95-
Ok(doc)
119+
Ok(()) // it's work but is better return with document
96120
}
97121

98-
pub async fn _delete(query: bson::Document) -> Result<Option<ArticleModel>> {
122+
pub async fn _delete(query: bson::oid::ObjectId) -> Result<mongodb::results::DeleteResult> {
99123
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");
100124
let db = Client::with_uri_str(&database_url).await?.database(MONGO_DB);
101125

102-
let doc = ArticleModel::find_one(&db, query, None).await?;
103-
println!("{:?}", doc);
126+
// This is bad code, how to dont pass all params? -> need improve
127+
let to_delete = ArticleModel {
128+
id: serde::__private::Some(query),
129+
author: String::from(""),
130+
title: String::from(""),
131+
content: String::from(""),
132+
created_at: String::from(""),
133+
};
134+
135+
let doc = ArticleModel::delete(&to_delete, &db).await?;
104136

105137
Ok(doc)
106138
}
107-
108-
139+
109140
}

src/articles/routes.rs

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,11 @@ use actix_web::{get, post, put, delete, web, HttpResponse, Responder};
22
use bson::doc;
33
use mongodb::{bson};
44
use bson::oid::ObjectId;
5-
use serde::{Deserialize, Serialize};
65

76
use crate::articles::{article};
87

9-
#[derive(Serialize, Deserialize)]
10-
pub struct ArticleUpdateRequest {
11-
#[serde(rename = "_id")]
12-
pub _id: String,
13-
pub author: String,
14-
pub title: String,
15-
pub content: String,
16-
pub created_at: String,
17-
}
18-
198
/**
209
* Crud Basic Operations
21-
* @todo -> refactor remove and update methods
2210
*/
2311

2412
#[get("/articles")]
@@ -54,21 +42,21 @@ pub async fn store(article: web::Json<article::ArticleRequest>) -> impl Responde
5442

5543
#[delete("/articles/{id}")]
5644
pub async fn remove(id: web::Path<String>) -> impl Responder {
57-
let object_id = ObjectId::with_string(&id).unwrap();
58-
let deleted = article::_delete(doc! { "_id": object_id }).await;
59-
45+
let object_id = match ObjectId::with_string(&id) {
46+
Ok(obj) => obj,
47+
Err(_) => ObjectId::with_string("").unwrap() // This is bad code -> need improve
48+
};
49+
50+
let deleted = article::_delete(object_id).await;
6051
match deleted {
6152
Ok(deleted) => HttpResponse::Ok().json(deleted),
6253
_ => HttpResponse::InternalServerError().finish()
6354
}
6455
}
6556

66-
// @todo -> Conseguir pegar o path junto com o body, só consegui pegar um dos dois
6757
#[put("/articles/{id}")]
68-
pub async fn update(article: web::Json<ArticleUpdateRequest>) -> impl Responder {
69-
let doc = doc!{"$set": doc! {"author": &article.author, "created_at": &article.created_at, "title": &article.title, "content": &article.content}};
70-
let object_id = ObjectId::with_string(&article._id).unwrap();
71-
let updated = article::_update(doc, doc! { "_id": object_id }).await;
58+
pub async fn update(article: web::Json<article::ArticleUpdateRequest>) -> impl Responder {
59+
let updated = article::_update(article).await;
7260

7361
match updated {
7462
Ok(updated) => HttpResponse::Ok().json(updated),

0 commit comments

Comments
 (0)