mirror of
https://gitlab.com/comunic/comunicapiv3
synced 2025-01-05 18:38:51 +00:00
94 lines
2.6 KiB
Rust
94 lines
2.6 KiB
Rust
//! # User Web Socket Request handler
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use serde::Serialize;
|
|
|
|
use crate::api_data::http_error::HttpError;
|
|
use crate::routes::RequestResult;
|
|
use crate::data::base_request_handler::{BaseRequestHandler, RequestValue};
|
|
use crate::data::error::ResultBoxError;
|
|
use crate::data::user_token::UserAccessToken;
|
|
use crate::data::user_ws_connection::UserWsConnection;
|
|
|
|
pub enum UserWsResponseType {
|
|
SUCCESS,
|
|
ERROR,
|
|
}
|
|
|
|
pub struct UserWsResponse {
|
|
pub r#type: UserWsResponseType,
|
|
pub content: serde_json::Value,
|
|
}
|
|
|
|
pub struct UserWsRequestHandler {
|
|
connection: UserWsConnection,
|
|
args: HashMap<String, RequestValue>,
|
|
response: Option<UserWsResponse>,
|
|
}
|
|
|
|
impl UserWsRequestHandler {
|
|
pub fn new(connection: &UserWsConnection, args: HashMap<String, String>) -> UserWsRequestHandler {
|
|
UserWsRequestHandler {
|
|
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) -> UserWsResponse {
|
|
if !self.has_response() {
|
|
self.success("Request done.").unwrap();
|
|
}
|
|
|
|
return self.response.unwrap();
|
|
}
|
|
|
|
/// Get a pointer to the websocket connection
|
|
pub fn get_conn(&self) -> &UserWsConnection {
|
|
&self.connection
|
|
}
|
|
|
|
/// Update information about the WebSocket connection
|
|
pub fn update_conn<H>(&mut self, do_updates: H) -> ResultBoxError where H: FnOnce(&mut UserWsConnection) {
|
|
self.connection = self.connection.clone().replace(do_updates);
|
|
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl BaseRequestHandler for UserWsRequestHandler {
|
|
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(UserWsResponse {
|
|
r#type: UserWsResponseType::SUCCESS,
|
|
content: serde_json::to_value(response)?,
|
|
});
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn set_error(&mut self, error: HttpError) {
|
|
self.response = Some(UserWsResponse {
|
|
r#type: UserWsResponseType::ERROR,
|
|
content: serde_json::Value::String(error.error.message),
|
|
});
|
|
}
|
|
|
|
fn remote_ip(&self) -> String {
|
|
self.connection.remote_ip.to_string()
|
|
}
|
|
|
|
fn user_access_token(&self) -> Option<&UserAccessToken> {
|
|
Some(&self.connection.user_token)
|
|
}
|
|
} |