structural improvements

This commit is contained in:
Yehowshua Immanuel 2025-01-07 08:54:07 -05:00
parent 1634ea7056
commit cf3c395850
3 changed files with 35 additions and 20 deletions

View file

@ -17,6 +17,7 @@ Now open `http://127.0.0.1:8080` in your browser.
- [ ] `EventHandlers.onMessage` should inject successfully decoded message into - [ ] `EventHandlers.onMessage` should inject successfully decoded message into
Msg type directly... Msg type directly...
- [ ] Run `uglify` twice as per [this link](https://github.com/rtfeldman/elm-spa-example/tree/master?tab=readme-ov-file#production-build) - [ ] Run `uglify` twice as per [this link](https://github.com/rtfeldman/elm-spa-example/tree/master?tab=readme-ov-file#production-build)
- [ ] Frontend should initiate with TimeRequest
- [ ] JSONify backend code for all send/receive - [ ] JSONify backend code for all send/receive
- [ ] Backend should only communicate over websocket - [ ] Backend should only communicate over websocket
- [ ] Close websocket after 15s of no response(from frontend) to websocket pings - [ ] Close websocket after 15s of no response(from frontend) to websocket pings

View file

@ -1,14 +1,27 @@
use actix_web_actors::ws::WebsocketContext;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Debug)]
#[derive(Serialize)]
pub enum DownMsg { pub enum DownMsg {
Greeting(String), Greeting(String),
TimeUpdate(String), TimeUpdate(String),
} }
#[derive(Deserialize, Debug)]
#[derive(Deserialize)]
pub enum UpMsg { pub enum UpMsg {
RequestGreet(String) RequestGreet(String),
}
pub fn msg_handler(
msg: UpMsg,
ws: &mut crate::MyWebSocket,
ctx: &mut WebsocketContext<crate::MyWebSocket>,
) {
match msg {
UpMsg::RequestGreet(name) => {
let greeting = format!("Hello, {}!", name);
let response = crate::DownMsg::Landing(DownMsg::Greeting(greeting));
ws.send_down_msg(response, ctx);
}
}
} }

View file

@ -2,25 +2,24 @@ use actix::prelude::*;
use actix_files::Files; use actix_files::Files;
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder}; use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder};
use actix_web_actors::ws; use actix_web_actors::ws;
use chrono::Local;
use log::info; use log::info;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{fs, time::Duration}; use std::{fs, time::Duration};
use chrono::Local;
mod landing; mod landing;
#[derive(Serialize)] #[derive(Serialize, Debug)]
enum DownMsg { pub enum DownMsg {
Landing(landing::DownMsg), Landing(landing::DownMsg),
} }
#[derive(Deserialize)] #[derive(Deserialize, Debug)]
enum UpMsg { enum UpMsg {
Landing(landing::UpMsg), Landing(landing::UpMsg),
} }
/// WebSocket actor pub struct MyWebSocket;
struct MyWebSocket;
impl Actor for MyWebSocket { impl Actor for MyWebSocket {
type Context = ws::WebsocketContext<Self>; type Context = ws::WebsocketContext<Self>;
@ -46,17 +45,10 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWebSocket {
) { ) {
match msg { match msg {
Ok(ws::Message::Text(text)) => { Ok(ws::Message::Text(text)) => {
// Attempt to decode the incoming message
if let Ok(up_msg) = serde_json::from_str::<UpMsg>(&text) { if let Ok(up_msg) = serde_json::from_str::<UpMsg>(&text) {
match up_msg { match up_msg {
UpMsg::Landing(landing::UpMsg::RequestGreet(name)) => { UpMsg::Landing(msg) =>
let greeting = format!("Hello, {}!", name); landing::msg_handler(msg, self, ctx),
let response = DownMsg::Landing(landing::DownMsg::Greeting(greeting));
if let Ok(json_response) = serde_json::to_string(&response) {
ctx.text(json_response);
}
}
} }
} }
} }
@ -68,6 +60,15 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWebSocket {
} }
} }
impl MyWebSocket {
fn send_down_msg(&self, down_msg: DownMsg, ctx: &mut ws::WebsocketContext<Self>) {
if let Ok(serialized_msg) = serde_json::to_string(&down_msg) {
ctx.text(serialized_msg);
} else {
log::error!("Failed to serialize DownMsg {:?}", down_msg);
}
}
}
async fn websocket_handler(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { async fn websocket_handler(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
ws::start(MyWebSocket {}, &req, stream) ws::start(MyWebSocket {}, &req, stream)