Skip to content

Commit 4f1380b

Browse files
Merge pull request #8 from LucasWerey/Marine
Marine
2 parents fe9b2a3 + 2ca1683 commit 4f1380b

File tree

9 files changed

+262
-8
lines changed

9 files changed

+262
-8
lines changed

Api/Readme.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,23 @@ curl -X POST -H "Content-Type: application/json" -d '{
6666
"lastname": "Last Name",
6767
"email": "user@example.com",
6868
"password": "password",
69-
"statut": "Status",
69+
"statut": "Status"
7070
7171
}' http://127.0.0.1:8000/user
7272
```
7373

74+
curl -X POST -H "Content-Type: application/json" -d '{
75+
"duree":5,
76+
"niveau": "BAC+5",
77+
"type_contrat": "alternance",
78+
"date_debut": {
79+
"$date": {"$numberLong": "1644566400000"}
80+
},
81+
"lieu": "Paris",
82+
"recherche": true
83+
84+
}' http://127.0.0.1:8000/student
85+
7486
### Get All Users - `GET /users`
7587

7688
Returns a list of all users in the system. No request body is required for this endpoint.
@@ -107,6 +119,20 @@ curl -X PUT -H "Content-Type: application/json" -d '{
107119
}' http://127.0.0.1:8000/user/<id>
108120
```
109121

122+
curl -X PUT -H "Content-Type: application/json" -d '{
123+
"duree":4,
124+
"niveau": "BAC+4",
125+
"type_contrat": "stage",
126+
"date_debut": {
127+
"$date": {
128+
"$numberLong": "1704712581950"
129+
}
130+
},
131+
"lieu": "Paris",
132+
"recherche": false
133+
134+
}' http://127.0.0.1:8000/student/65a17960c47012ed8f140bfe
135+
110136
### Delete User - `DELETE /user/<id>`
111137

112138
Deletes a specific user. Replace `<id>` with the ID of the user you want to delete. No request body is required for this endpoint.

Api/src/api/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
pub mod user_api;
1+
pub mod user_api;
2+
pub mod students_api;

Api/src/api/students_api.rs

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
use crate::{models::students_model::Students, models::user_model::User, repository::mongodb_repo::MongoRepo};
2+
use mongodb::{bson::oid::ObjectId, results::InsertOneResult};
3+
use rocket::{http::Status, serde::json::Json, State};
4+
use bcrypt::{hash, DEFAULT_COST};
5+
use bcrypt::verify;
6+
use jsonwebtoken::{encode, EncodingKey, Header, Algorithm};
7+
use std::collections::BTreeMap;
8+
use rocket::serde::Serialize;
9+
use rocket::serde::Deserialize;
10+
use chrono::{Utc, Duration};
11+
use std::env;
12+
use dotenv::dotenv;
13+
use mongodb::bson::DateTime as BsonDateTime;
14+
15+
#[post("/student", data = "<new_students>")]
16+
pub fn create_students(
17+
db: &State<MongoRepo>,
18+
new_students: Json<Students>,
19+
) -> Result<Json<InsertOneResult>, Status> {
20+
let data = Students {
21+
id: None,
22+
duree: new_students.duree,
23+
niveau: new_students.niveau.to_owned(),
24+
type_contrat: new_students.type_contrat.to_owned(),
25+
date_debut: new_students.date_debut,
26+
lieu: new_students.lieu.to_owned(),
27+
recherche: new_students.recherche,
28+
29+
};
30+
let students_detail = db.create_students(data);
31+
match students_detail {
32+
Ok(students) => Ok(Json(students)),
33+
Err(_) => Err(Status::InternalServerError),
34+
}
35+
}
36+
37+
38+
#[get("/student/<path>")]
39+
pub fn get_students(db: &State<MongoRepo>, path: String) -> Result<Json<Students>, Status> {
40+
let id = path;
41+
if id.is_empty() {
42+
return Err(Status::BadRequest);
43+
};
44+
let students_detail = db.get_students(&id);
45+
match students_detail {
46+
Ok(students) => Ok(Json(students)),
47+
Err(_) => Err(Status::InternalServerError),
48+
}
49+
}
50+
51+
#[put("/student/<path>", data = "<new_students>")]
52+
pub fn update_students(
53+
db: &State<MongoRepo>,
54+
path: String,
55+
new_students: Json<Students>,
56+
) -> Result<Json<Students>, Status> {
57+
let id = path;
58+
if id.is_empty() {
59+
return Err(Status::BadRequest);
60+
};
61+
let data = Students {
62+
id: Some(ObjectId::parse_str(&id).unwrap()),
63+
duree: new_students.duree,
64+
niveau: new_students.niveau.to_owned(),
65+
type_contrat: new_students.type_contrat.to_owned(),
66+
date_debut: new_students.date_debut,
67+
lieu: new_students.lieu.to_owned(),
68+
recherche: new_students.recherche,
69+
};
70+
let update_result = db.update_students(&id, data);
71+
match update_result {
72+
Ok(update) => {
73+
if update.matched_count == 1 {
74+
let updated_students_info = db.get_students(&id);
75+
return match updated_students_info {
76+
Ok(students) => Ok(Json(students)),
77+
Err(_) => Err(Status::InternalServerError),
78+
};
79+
} else {
80+
return Err(Status::NotFound);
81+
}
82+
}
83+
Err(_) => Err(Status::InternalServerError),
84+
}
85+
}
86+
87+
#[delete("/student/<path>")]
88+
pub fn delete_students(db: &State<MongoRepo>, path: String) -> Result<Json<&str>, Status> {
89+
let id = path;
90+
if id.is_empty() {
91+
return Err(Status::BadRequest);
92+
};
93+
let result = db.delete_students(&id);
94+
match result {
95+
Ok(res) => {
96+
if res.deleted_count == 1 {
97+
return Ok(Json("Students successfully deleted!"));
98+
} else {
99+
return Err(Status::NotFound);
100+
}
101+
}
102+
Err(_) => Err(Status::InternalServerError),
103+
}
104+
}
105+
106+
#[get("/students")]
107+
pub fn get_all_students(db: &State<MongoRepo>) -> Result<Json<Vec<Students>>, Status> {
108+
let students = db.get_all_students();
109+
match students {
110+
Ok(students) => Ok(Json(students)),
111+
Err(_) => Err(Status::InternalServerError),
112+
}
113+
}

Api/src/api/user_api.rs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::{models::user_model::User,models::user_model::LoginData, repository::mongodb_repo::MongoRepo};
1+
use crate::{models::user_model::User,models::user_model::LoginData,models::students_model::Students, repository::mongodb_repo::MongoRepo};
22
use mongodb::{bson::oid::ObjectId, results::InsertOneResult};
33
use rocket::{http::Status, serde::json::Json, State};
44
use bcrypt::{hash, DEFAULT_COST};
@@ -37,9 +37,26 @@ pub fn create_user(
3737
statut: new_user.statut.to_owned(),
3838
date: Some(BsonDateTime::from_millis(Utc::now().timestamp_millis())),
3939
};
40-
let user_detail = db.create_user(data);
40+
let user_clone = data.clone();
41+
let user_detail = db.create_user(user_clone);
4142
match user_detail {
42-
Ok(user) => Ok(Json(user)),
43+
Ok(user) =>{
44+
if data.statut == "student" {
45+
let student_data = Students {
46+
id: data.id.as_ref().map(|id| id).copied(), // Utilisez le même ID que l'utilisateur
47+
duree: 0, // Vous devez définir une valeur par défaut ou récupérer cette information ailleurs
48+
niveau: String::new(),
49+
type_contrat: String::new(),
50+
date_debut: BsonDateTime::now(),
51+
lieu: String::new(),
52+
recherche: false,
53+
};
54+
55+
// Créez l'étudiant
56+
let _ = db.create_students(student_data);
57+
}
58+
Ok(Json(user))
59+
},
4360
Err(_) => Err(Status::InternalServerError),
4461
}
4562
}

Api/src/main.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use rocket::http::Method;
88
use rocket_cors::{AllowedHeaders, AllowedOrigins, CorsOptions};
99

1010
use api::user_api::{create_user, get_user, update_user, delete_user, get_all_users, login};
11+
use api::students_api::{create_students, get_students, update_students, delete_students,get_all_students };
1112
use repository::mongodb_repo::MongoRepo;
1213

1314
#[launch]
@@ -28,5 +29,5 @@ fn rocket() -> _ {
2829
rocket::build()
2930
.attach(cors)
3031
.manage(db)
31-
.mount("/", routes![create_user, get_user, update_user, delete_user, get_all_users, login])
32+
.mount("/", routes![create_user, get_user, update_user, delete_user, get_all_users, login,create_students, get_students, update_students, delete_students, get_all_students ])
3233
}

Api/src/models/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
pub mod user_model;
2+
pub mod students_model;

Api/src/models/students_model.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
use mongodb::bson::oid::ObjectId;
2+
use serde::{Serialize, Deserialize};
3+
use mongodb::bson::DateTime as BsonDateTime;
4+
5+
6+
7+
#[derive(Debug, Serialize, Deserialize)]
8+
pub struct Students {
9+
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
10+
pub id: Option<ObjectId>,
11+
pub duree: i32,
12+
pub niveau: String,
13+
pub type_contrat: String,
14+
pub date_debut: BsonDateTime,
15+
pub lieu: String,
16+
pub recherche: bool,
17+
}
18+
19+

Api/src/models/user_model.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use mongodb::bson::oid::ObjectId;
22
use serde::{Serialize, Deserialize};
33
use mongodb::bson::DateTime as BsonDateTime;
44

5-
#[derive(Debug, Serialize, Deserialize)]
5+
#[derive(Debug, Serialize, Deserialize, Clone)]
66
pub struct User {
77
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
88
pub id: Option<ObjectId>,

Api/src/repository/mongodb_repo.rs

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@ use mongodb::{
88
sync::{Client, Collection},
99
};
1010
use crate::models::user_model::User;
11+
use crate::models::students_model::Students;
1112

1213
pub struct MongoRepo {
1314
col: Collection<User>,
15+
col2: Collection<Students>
1416
}
1517

1618

@@ -24,7 +26,8 @@ pub struct MongoRepo {
2426
let client = Client::with_uri_str(uri).unwrap();
2527
let db = client.database("Pfe");
2628
let col: Collection<User> = db.collection("users");
27-
MongoRepo { col }
29+
let col2: Collection<Students>=db.collection("students");
30+
MongoRepo { col, col2 }
2831
}
2932

3033
pub fn create_user(&self, new_user: User) -> Result<InsertOneResult, Error> {
@@ -109,4 +112,77 @@ pub struct MongoRepo {
109112
.expect("Error getting user's detail");
110113
Ok(user_detail.unwrap())
111114
}
115+
116+
pub fn create_students(&self, new_students: Students) -> Result<InsertOneResult, Error> {
117+
let new_doc = Students {
118+
id: None,
119+
duree: new_students.duree,
120+
niveau: new_students.niveau,
121+
type_contrat: new_students.type_contrat,
122+
date_debut: new_students.date_debut,
123+
lieu: new_students.lieu,
124+
recherche: new_students.recherche
125+
126+
};
127+
let students = self
128+
.col2
129+
.insert_one(new_doc, None)
130+
.ok()
131+
.expect("Error creating students");
132+
Ok(students)
133+
}
134+
135+
pub fn get_students(&self, id: &String) -> Result<Students, Error> {
136+
let obj_id = ObjectId::parse_str(id).unwrap();
137+
let filter = doc! {"_id": obj_id};
138+
let students_detail = self
139+
.col2
140+
.find_one(filter, None)
141+
.ok()
142+
.expect("Error getting students detail");
143+
Ok(students_detail.unwrap())
144+
}
145+
146+
pub fn update_students(&self, id: &String, new_students: Students) -> Result<UpdateResult, Error> {
147+
let obj_id = ObjectId::parse_str(id).unwrap();
148+
let filter = doc! {"_id": obj_id};
149+
let new_doc = doc! {
150+
"$set":
151+
{
152+
"duree": new_students.duree,
153+
"niveau": new_students.niveau,
154+
"type_contrat": new_students.type_contrat,
155+
"date_debut": new_students.date_debut,
156+
"lieu": new_students.lieu,
157+
"recherche": new_students.recherche
158+
},
159+
};
160+
let updated_doc = self
161+
.col2
162+
.update_one(filter, new_doc, None)
163+
.ok()
164+
.expect("Error updating students");
165+
Ok(updated_doc)
166+
}
167+
168+
pub fn delete_students(&self, id: &String) -> Result<DeleteResult, Error> {
169+
let obj_id = ObjectId::parse_str(id).unwrap();
170+
let filter = doc! {"_id": obj_id};
171+
let students_detail = self
172+
.col2
173+
.delete_one(filter, None)
174+
.ok()
175+
.expect("Error deleting students");
176+
Ok(students_detail)
177+
}
178+
179+
pub fn get_all_students(&self) -> Result<Vec<Students>, Error> {
180+
let cursors = self
181+
.col2
182+
.find(None, None)
183+
.ok()
184+
.expect("Error getting list of students");
185+
let students = cursors.map(|doc| doc.unwrap()).collect();
186+
Ok(students)
187+
}
112188
}

0 commit comments

Comments
 (0)