Implement functionality to check for existing member with NTNU username

This commit is contained in:
Sebastian H. Gabrielli 2023-12-24 00:27:18 +01:00
parent 48bb2ab839
commit bf84ff6e33

View File

@ -50,7 +50,7 @@ struct MinimalMemberWithoutId {
} }
#[derive(Responder)] #[derive(Responder)]
#[response(status = 500, content_type = "json")] #[response(status = 500, content_type = "text/plain")]
struct ErrorResponder { struct ErrorResponder {
message: String message: String
} }
@ -81,6 +81,21 @@ async fn add_member(db: &State<DatabaseConnection>, minimalMemberWithoutId: Json
// Grab the database connection // Grab the database connection
let db = db as &DatabaseConnection; let db = db as &DatabaseConnection;
// Check if a member with the same NTNU username already exists
let matching_member: Option<members::Model> = Members::find() // Find a member in the "Members" table
.filter(members::Column::NtnuUsername.eq(minimalMemberWithoutId.ntnuUsername.to_owned())) // Filter by the provided username in the NtnuUsername column
.one(db) // We only care about one result
.await?; // Wait for the result
// If a member exists return an error
if matching_member.is_some() {
return Err(
ErrorResponder {
message: "A member with this NTNU username already exists".to_string(),
}
)
}
// Create the new member info from the provided JSON // Create the new member info from the provided JSON
let new_member = members::ActiveModel { let new_member = members::ActiveModel {
ntnu_username: ActiveValue::Set(minimalMemberWithoutId.ntnuUsername.to_owned()), ntnu_username: ActiveValue::Set(minimalMemberWithoutId.ntnuUsername.to_owned()),
@ -108,6 +123,7 @@ async fn add_member(db: &State<DatabaseConnection>, minimalMemberWithoutId: Json
}, },
} }
// Put the fetched info into a minimal member for returning
let member = MinimalMember { let member = MinimalMember {
id: new_member.id, id: new_member.id,
ntnuUsername: new_member.ntnu_username, ntnuUsername: new_member.ntnu_username,