//! # 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, response: Option, } impl WsRequestHandler { pub fn new(connection: &WsConnection, args: HashMap) -> 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(&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 { Ok(self.connection.user_id.clone()) } }