use super::handler::ConnectionId;
use super::rooms::{RoomId, RoomMember};
use axum::extract::ws::Message;
#[derive(Debug, Clone)]
pub struct JoinRoomRequest {
pub room_id: RoomId,
pub member: RoomMember,
}
impl JoinRoomRequest {
#[must_use]
pub fn new(room_id: impl Into<RoomId>, member: RoomMember) -> Self {
Self {
room_id: room_id.into(),
member,
}
}
}
#[derive(Debug, Clone)]
pub struct LeaveRoomRequest {
pub room_id: RoomId,
pub connection_id: ConnectionId,
}
impl LeaveRoomRequest {
#[must_use]
pub fn new(room_id: impl Into<RoomId>, connection_id: ConnectionId) -> Self {
Self {
room_id: room_id.into(),
connection_id,
}
}
}
#[derive(Debug, Clone)]
pub struct BroadcastToRoom {
pub room_id: RoomId,
pub message: Message,
pub exclude_sender: Option<ConnectionId>,
}
impl BroadcastToRoom {
#[must_use]
pub fn new(room_id: impl Into<RoomId>, message: Message) -> Self {
Self {
room_id: room_id.into(),
message,
exclude_sender: None,
}
}
#[must_use]
pub fn excluding_sender(
room_id: impl Into<RoomId>,
message: Message,
sender: ConnectionId,
) -> Self {
Self {
room_id: room_id.into(),
message,
exclude_sender: Some(sender),
}
}
}
#[derive(Debug, Clone)]
pub struct ConnectionDisconnected {
pub connection_id: ConnectionId,
}
impl ConnectionDisconnected {
#[must_use]
pub fn new(connection_id: ConnectionId) -> Self {
Self { connection_id }
}
}
#[derive(Debug, Clone)]
pub struct GetRoomInfo {
pub room_id: RoomId,
}
impl GetRoomInfo {
#[must_use]
pub fn new(room_id: impl Into<RoomId>) -> Self {
Self {
room_id: room_id.into(),
}
}
}
#[derive(Debug, Clone)]
pub struct RoomInfoResponse {
pub room_id: RoomId,
pub member_count: usize,
pub exists: bool,
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::mpsc;
#[test]
fn test_join_room_request() {
let (tx, _rx) = mpsc::channel(32);
let member = RoomMember::new(ConnectionId::new(), tx);
let request = JoinRoomRequest::new("test-room", member);
assert_eq!(request.room_id.as_str(), "test-room");
}
#[test]
fn test_leave_room_request() {
let conn_id = ConnectionId::new();
let request = LeaveRoomRequest::new("test-room", conn_id);
assert_eq!(request.room_id.as_str(), "test-room");
assert_eq!(request.connection_id, conn_id);
}
#[test]
fn test_broadcast_excluding_sender() {
let sender_id = ConnectionId::new();
let msg = Message::Text("hello".into());
let broadcast = BroadcastToRoom::excluding_sender("room1", msg, sender_id);
assert_eq!(broadcast.exclude_sender, Some(sender_id));
}
}