summaryrefslogtreecommitdiff
path: root/gateway/src/connection/utils.rs
blob: fb07229f601e2b005bfc2fa0c1b53e81e8da6b24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use std::str::from_utf8;
use tokio_tungstenite::tungstenite::Message;
use log::info;

use crate::error::GatewayError;

use super::Connection;

impl Connection {

    /// Handles the websocket events and calls the _handle_discord_message function for the deserialization.
    pub(super) async fn _handle_message(
        &mut self,
        data: &Message,
    ) -> Result<crate::payloads::gateway::Message, GatewayError> {
        match data {
            Message::Text(text) => self._handle_discord_message(&text).await,
            Message::Binary(message) => {
                match from_utf8(message) {
                    Ok(data) => self._handle_discord_message(data).await,
                    Err(err) => Err(GatewayError::from(err.to_string())),
                }
            },
            Message::Close(close_frame) => {
                info!("Discord connection closed {:?}", close_frame);
                Err(GatewayError::from("connection closed".to_string()))
            },
            _ => Err(GatewayError::from(format!("unknown variant of message specified to the handler {}", data).to_string())),
        }
    }

    /// Handle the decompression and deserialization process of a discord payload.
    pub(super) async fn _handle_discord_message(
        &mut self,
        raw_message: &str,
    ) -> Result<crate::payloads::gateway::Message, GatewayError> {
        match serde_json::from_str(raw_message) {
            Ok(message) => Ok(message),
            Err(err) => Err(GatewayError::from(err.to_string())),
        }
    }
}