mirror of
https://gitlab.com/comunic/comunicapiv3
synced 2025-01-08 11:42:35 +00:00
86 lines
2.2 KiB
Rust
86 lines
2.2 KiB
Rust
|
//! # User Web Socket Request handler
|
||
|
|
||
|
use std::collections::HashMap;
|
||
|
|
||
|
use serde::Serialize;
|
||
|
|
||
|
use crate::api_data::http_error::HttpError;
|
||
|
use crate::controllers::routes::RequestResult;
|
||
|
use crate::controllers::user_ws_controller::WsConnection;
|
||
|
use crate::data::base_request_handler::{BaseRequestHandler, RequestValue};
|
||
|
use crate::data::error::ResultBoxError;
|
||
|
use crate::data::user::UserID;
|
||
|
|
||
|
pub enum WsResponseType {
|
||
|
SUCCESS,
|
||
|
ERROR,
|
||
|
}
|
||
|
|
||
|
pub struct WsResponse {
|
||
|
pub r#type: WsResponseType,
|
||
|
pub content: serde_json::Value,
|
||
|
}
|
||
|
|
||
|
pub struct WsRequestHandler {
|
||
|
connection: WsConnection,
|
||
|
args: HashMap<String, RequestValue>,
|
||
|
response: Option<WsResponse>,
|
||
|
}
|
||
|
|
||
|
impl WsRequestHandler {
|
||
|
pub fn new(connection: &WsConnection, args: HashMap<String, String>) -> WsRequestHandler {
|
||
|
WsRequestHandler {
|
||
|
connection: connection.clone(),
|
||
|
args: args.into_iter().map(|f| (f.0, RequestValue::String(f.1))).collect(),
|
||
|
response: None,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/// Check if a response has been set
|
||
|
pub fn has_response(&self) -> bool {
|
||
|
self.response.is_some()
|
||
|
}
|
||
|
|
||
|
/// Get the response to the request
|
||
|
pub fn response(mut self) -> WsResponse {
|
||
|
if !self.has_response() {
|
||
|
self.success("Request done.").unwrap();
|
||
|
}
|
||
|
|
||
|
return self.response.unwrap();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl BaseRequestHandler for WsRequestHandler {
|
||
|
fn post_parameter_opt(&self, name: &str) -> Option<&RequestValue> {
|
||
|
self.args.get(name)
|
||
|
}
|
||
|
|
||
|
fn set_response<T: Serialize>(&mut self, response: T) -> RequestResult {
|
||
|
self.response = Some(WsResponse {
|
||
|
r#type: WsResponseType::SUCCESS,
|
||
|
content: serde_json::to_value(response)?,
|
||
|
});
|
||
|
|
||
|
Ok(())
|
||
|
}
|
||
|
|
||
|
fn set_error(&mut self, error: HttpError) {
|
||
|
self.response = Some(WsResponse {
|
||
|
r#type: WsResponseType::ERROR,
|
||
|
content: serde_json::Value::String(error.error.message),
|
||
|
});
|
||
|
}
|
||
|
|
||
|
fn remote_ip(&self) -> String {
|
||
|
self.connection.remote_ip.to_string()
|
||
|
}
|
||
|
|
||
|
fn user_id_opt_ref(&self) -> Option<&UserID> {
|
||
|
Some(&self.connection.user_id)
|
||
|
}
|
||
|
|
||
|
fn user_id(&self) -> ResultBoxError<UserID> {
|
||
|
Ok(self.connection.user_id.clone())
|
||
|
}
|
||
|
}
|