Create and implement add_member function

This commit is contained in:
Sebastian H. Gabrielli 2023-12-24 00:18:33 +01:00
parent 35971d14d1
commit 48bb2ab839
2 changed files with 63 additions and 1 deletions

View File

@ -1,5 +1,6 @@
// Webserver
#[macro_use] extern crate rocket;
use rocket::{State, Error};
use rocket::response::status;
use rocket::serde::{Serialize, Deserialize, json::Json};
@ -31,6 +32,23 @@ struct Member {
rfidCards: Vec<RfidCard>
}
#[derive(Serialize, Deserialize)]
struct MinimalMember {
id: i32,
ntnuUsername: String,
firstName: String,
lastName: String,
email: String,
}
#[derive(Serialize, Deserialize)]
struct MinimalMemberWithoutId {
ntnuUsername: String,
firstName: String,
lastName: String,
email: String,
}
#[derive(Responder)]
#[response(status = 500, content_type = "json")]
struct ErrorResponder {
@ -58,6 +76,49 @@ fn index() -> &'static str {
"Hello, world!\nNothing useful is served here."
}
#[post("/member", data = "<minimalMemberWithoutId>")]
async fn add_member(db: &State<DatabaseConnection>, minimalMemberWithoutId: Json<MinimalMemberWithoutId>) -> Result<Json<MinimalMember>, ErrorResponder> {
// Grab the database connection
let db = db as &DatabaseConnection;
// Create the new member info from the provided JSON
let new_member = members::ActiveModel {
ntnu_username: ActiveValue::Set(minimalMemberWithoutId.ntnuUsername.to_owned()),
first_name: ActiveValue::Set(minimalMemberWithoutId.firstName.to_owned()),
last_name: ActiveValue::Set(minimalMemberWithoutId.lastName.to_owned()),
email: ActiveValue::Set(minimalMemberWithoutId.email.to_owned()),
balance: ActiveValue::Set(0),
image_preference: ActiveValue::Set("Money".to_string()),
..Default::default()
};
// Add the new member to the database
let res = Members::insert(new_member).exec(db).await?;
// Fetch the member's info back from the DB to verify
let new_member;
match Members::find_by_id(res.last_insert_id).one(db).await? {
Some(model) => new_member = model,
None => {
return Err(
ErrorResponder {
message: format!("Failed to fetch member for verification of creating new member with ID. memberId: {}", res.last_insert_id)
}
);
},
}
let member = MinimalMember {
id: new_member.id,
ntnuUsername: new_member.ntnu_username,
firstName: new_member.first_name,
lastName: new_member.last_name,
email: new_member.email,
};
Ok(Json(member))
}
#[get("/member/<memberId>")]
async fn get_member_by_id(db: &State<DatabaseConnection>, memberId: i32) -> Result<Json<Member>, ErrorResponder> {
let db = db as &DatabaseConnection;
@ -105,6 +166,7 @@ async fn rocket() -> _ {
.manage(db)
.mount("/", routes![
index,
get_member_by_id
get_member_by_id,
add_member
])
}

BIN
test.db

Binary file not shown.