use crate::message::{NotificationHandler, RequestBuilder, ResponseHandler};
use crate::model::ws_types::{JsonRpcNotification, JsonRpcRequest, JsonRpcResponse};
#[derive(Debug)]
pub struct MessageBuilder {
request_builder: RequestBuilder,
response_handler: ResponseHandler,
notification_handler: NotificationHandler,
}
impl Default for MessageBuilder {
fn default() -> Self {
Self::new()
}
}
impl MessageBuilder {
#[must_use]
pub fn new() -> Self {
Self {
request_builder: RequestBuilder::new(),
response_handler: ResponseHandler::new(),
notification_handler: NotificationHandler::new(),
}
}
pub fn request_builder(&mut self) -> &mut RequestBuilder {
&mut self.request_builder
}
#[must_use]
pub fn response_handler(&self) -> &ResponseHandler {
&self.response_handler
}
#[must_use]
pub fn notification_handler(&self) -> &NotificationHandler {
&self.notification_handler
}
pub fn parse_message(&self, data: &str) -> Result<MessageType, serde_json::Error> {
if let Ok(response) = self.response_handler.parse_response(data) {
return Ok(MessageType::Response(response));
}
if let Ok(notification) = self.notification_handler.parse_notification(data) {
return Ok(MessageType::Notification(notification));
}
Err(serde_json::Error::io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Unable to parse message",
)))
}
}
#[derive(Debug, Clone)]
pub enum MessageType {
Request(JsonRpcRequest),
Response(JsonRpcResponse),
Notification(JsonRpcNotification),
}