simple send message endpoint
This commit is contained in:
@@ -8,7 +8,7 @@ use axum::{
|
||||
use rusqlite::params;
|
||||
|
||||
use crate::chat::extractor::{
|
||||
AddUserConversationPayload, CreateConversationPayload
|
||||
AddUserConversationPayload, CreateConversationPayload, SendMessagePayload
|
||||
};
|
||||
use crate::utils::db_pool::{AppState};
|
||||
use crate::utils::auth::AuthClaims;
|
||||
@@ -61,7 +61,7 @@ pub async fn add_user_to_conv(
|
||||
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "prepare failed".to_string())
|
||||
};
|
||||
|
||||
if !statement.exists(params![user_id, payload.conv_id ])
|
||||
if !statement.exists(params![user_id, payload.conv_id])
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Query failed".to_string())).unwrap()
|
||||
{
|
||||
// Early exit if not creator
|
||||
@@ -87,4 +87,43 @@ pub async fn add_user_to_conv(
|
||||
|
||||
return (StatusCode::OK, "ok".to_string());
|
||||
|
||||
}
|
||||
|
||||
pub async fn send_message(
|
||||
State(state): State<AppState>,
|
||||
AuthClaims {user_id, hotel_id,username}: AuthClaims,
|
||||
SendMessagePayload(payload):SendMessagePayload
|
||||
) -> impl IntoResponse {
|
||||
|
||||
let pool = state.hotel_pools.get_pool(hotel_id);
|
||||
|
||||
let conn = match pool.get(){
|
||||
Ok(conn) => conn,
|
||||
Err(err) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("Pool error"))
|
||||
};
|
||||
|
||||
let mut statement = match conn.prepare(
|
||||
"SELECT 1 FROM conversation_participants WHERE user_id = ?1 AND conversation_id = ?2" ,
|
||||
){
|
||||
Ok(statement) => statement,
|
||||
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "prepare failed".to_string())
|
||||
};
|
||||
|
||||
if !statement.exists(params![user_id, payload.conv_id])
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Query failed".to_string())).unwrap()
|
||||
{
|
||||
// Early exit if not creator
|
||||
return ((StatusCode::FORBIDDEN, "Not the creator".to_string()));
|
||||
}
|
||||
|
||||
let result = conn.execute(
|
||||
"INSERT INTO message (sender_id, content, conversation_id) VALUES (?1, ?2, ?3)",
|
||||
params![&user_id, &payload.message, &payload.conv_id],
|
||||
);
|
||||
|
||||
match result {
|
||||
Ok(rows) if rows > 0 => (StatusCode::OK, "added message succesfully".to_string()),
|
||||
Ok(_) => (StatusCode::NOT_FOUND, "not able to add the message, conversation may not exist".to_string() ),
|
||||
Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, format!("Error when adding the message : {err}")),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user