Skip to main content

minesweeper_client/
client.rs

1use minesweeper_common::models::{CreateResponse, GameParams};
2use reqwest::Client;
3use url::Url;
4
5use crate::Result;
6
7/// HTTP client for minesweeper server API
8pub struct MinesweeperClient {
9    client: Client,
10    base_url: Url,
11}
12
13impl MinesweeperClient {
14    /// Create a new client connecting to the specified server URL
15    pub fn new(base_url: &str) -> Result<Self> {
16        let base_url = Url::parse(base_url)?;
17        let client = Client::new();
18
19        Ok(Self { client, base_url })
20    }
21
22    /// Create a new game with the specified parameters
23    /// Returns the game ID that can be used to connect via WebSocket
24    pub async fn create_game(&self, params: GameParams) -> Result<String> {
25        let create_url = self.base_url.join("/create")?;
26
27        let response = self.client.post(create_url).json(&params).send().await?;
28
29        if !response.status().is_success() {
30            return Err(format!("Failed to create game: {}", response.status()).into());
31        }
32
33        let create_response: CreateResponse = response.json().await?;
34        Ok(create_response.id)
35    }
36
37    /// Get the WebSocket URL for a game
38    pub fn websocket_url(&self, game_id: &str) -> Result<String> {
39        let mut ws_url = self.base_url.clone();
40        ws_url
41            .set_scheme(match self.base_url.scheme() {
42                "https" => "wss",
43                _ => "ws",
44            })
45            .map_err(|_| "Failed to set WebSocket scheme")?;
46        ws_url.set_path("/ws");
47        ws_url.set_query(Some(&format!("id={}", game_id)));
48
49        Ok(ws_url.to_string())
50    }
51}