common/emgauwa-lib/src/handlers/v1/ws/controllers.rs

52 lines
1.4 KiB
Rust

use crate::db::Schedule;
use crate::handlers::errors::ApiError;
use actix::{Actor, StreamHandler};
use actix_web::{get, web, HttpRequest, HttpResponse};
use actix_web_actors::ws;
use actix_web_actors::ws::ProtocolError;
use sqlx::{Pool, Sqlite};
use ws::Message;
struct ControllerWs {
pub pool: Pool<Sqlite>,
}
impl Actor for ControllerWs {
type Context = ws::WebsocketContext<Self>;
}
async fn get_schedules(pool: &mut Pool<Sqlite>) -> Result<Vec<Schedule>, ApiError> {
let mut pool_conn = pool.acquire().await?;
Ok(Schedule::get_all(&mut pool_conn).await?)
}
impl StreamHandler<Result<Message, ProtocolError>> for ControllerWs {
fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
let schedules = futures::executor::block_on(get_schedules(&mut self.pool)).unwrap();
let schedules_json = serde_json::to_string(&schedules).unwrap();
match msg {
Ok(Message::Ping(msg)) => ctx.pong(&msg),
Ok(Message::Text(_text)) => ctx.text(schedules_json),
_ => {}
}
}
}
#[get("/api/v1/ws/controllers")]
pub async fn index(
pool: web::Data<Pool<Sqlite>>,
req: HttpRequest,
stream: web::Payload,
) -> Result<HttpResponse, ApiError> {
let resp = ws::start(
ControllerWs {
pool: pool.get_ref().clone(),
},
&req,
stream,
)
.map_err(|_| ApiError::InternalError(String::from("error starting websocket")));
println!("{:?}", resp);
resp
}