screeps_rust_api/
api.rs

1use serde::{Serialize, de::DeserializeOwned};
2
3use crate::{
4    AllShardData, EncodedRoomTerrainData, MyInfoData, MyNameData, RoomStatusData, RoomTerrainData,
5    ShardTimeData, UserAllRoomsData, UserInfoData,
6    config::ScreepsConfig,
7    error::ScreepsResult,
8    http_client::*,
9    model::{RoomObjectsData, TokenData},
10};
11
12/// Screeps Api
13pub struct ScreepsApi {
14    /// http 客户端
15    pub http_client: ScreepsHttpClient,
16}
17
18impl ScreepsApi {
19    pub fn new(config: ScreepsConfig) -> Self {
20        let http_client = ScreepsHttpClient::new(config);
21        Self { http_client }
22    }
23
24    /// 登录获取 token 数据
25    pub async fn auth(&self) -> ScreepsResult<TokenData> {
26        self.http_client.auth().await
27    }
28
29    /// 请求接口
30    pub async fn request<T: Serialize, U: DeserializeOwned>(
31        &self,
32        method: Method,
33        path: &str,
34        body: Option<T>,
35    ) -> ScreepsResult<U> {
36        self.http_client.request(method, path, body).await
37    }
38
39    /// 获取自己的信息数据
40    pub async fn get_my_info(&self) -> ScreepsResult<MyInfoData> {
41        self.request::<AnyPayload, MyInfoData>(Get, "/auth/me", None)
42            .await
43    }
44
45    /// 获取我的名字
46    pub async fn get_my_name(&self) -> ScreepsResult<MyNameData> {
47        self.request::<AnyPayload, MyNameData>(Get, "/user/name", None)
48            .await
49    }
50
51    /// 获取玩家的所有房间
52    pub async fn get_user_rooms(&self, id: &str) -> ScreepsResult<UserAllRoomsData> {
53        self.request(Get, "/user/rooms", Some(&[("id", id)])).await
54    }
55
56    /// 根据用户名获取玩家信息
57    pub async fn get_user_info_by_name(&self, username: &str) -> ScreepsResult<UserInfoData> {
58        self.request(Get, "/user/find", Some(&[("username", username)]))
59            .await
60    }
61
62    /// 根据用户ID获取玩家信息
63    pub async fn get_user_info_by_id(&self, id: &str) -> ScreepsResult<UserInfoData> {
64        self.request(Get, "/user/find", Some(&[("id", id)])).await
65    }
66
67    /// 获取房间对象数据
68    /// 参数:
69    /// - room: 房间名称
70    /// - shard: shard 名称
71    pub async fn get_room_objects(
72        &self,
73        room: &str,
74        shard: &str,
75    ) -> ScreepsResult<RoomObjectsData> {
76        self.request(
77            Get,
78            "/game/room-objects",
79            Some(&[("room", room), ("shard", shard)]),
80        )
81        .await
82    }
83
84    /// 获取房间地形数据
85    pub async fn get_room_terrain(
86        &self,
87        room: &str,
88        shard: &str,
89    ) -> ScreepsResult<RoomTerrainData> {
90        self.request(
91            Get,
92            "/game/room-terrain",
93            Some(&[("room", room), ("shard", shard)]),
94        )
95        .await
96    }
97
98    /// 获取编码后的房间地形数据
99    pub async fn get_room_terrain_encoded(
100        &self,
101        room: &str,
102        shard: &str,
103    ) -> ScreepsResult<EncodedRoomTerrainData> {
104        self.request(
105            Get,
106            "/game/room-terrain",
107            Some(&[("room", room), ("shard", shard), ("encoded", "true")]),
108        )
109        .await
110    }
111
112    /// 获取房间状态数据
113    pub async fn get_room_status(&self, room: &str, shard: &str) -> ScreepsResult<RoomStatusData> {
114        self.request(
115            Get,
116            "/game/room-status",
117            Some(&[("room", room), ("shard", shard)]),
118        )
119        .await
120    }
121
122    /// 获取所有shard的信息
123    pub async fn get_shards(&self) -> ScreepsResult<AllShardData> {
124        self.request::<AnyPayload, AllShardData>(Get, "/game/shards/info", None)
125            .await
126    }
127
128    /// 获取指定 shard 的游戏时间
129    pub async fn get_shard_time(&self, shard: &str) -> ScreepsResult<ShardTimeData> {
130        self.request(Get, "/game/time", Some(&[("shard", shard)]))
131            .await
132    }
133}
134
135impl Default for ScreepsApi {
136    /// 默认实现只能调用无 token 要求的接口
137    fn default() -> Self {
138        let http_client = ScreepsHttpClient::new(ScreepsConfig::default());
139        Self { http_client }
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use crate::screeps_api_from_env;
147
148    #[tokio::test]
149    async fn test_get_my_info() {
150        let api = screeps_api_from_env!().unwrap();
151        let my_info = api.get_my_info().await.unwrap();
152        // println!("{}", my_info.user._id);
153        assert_eq!(my_info.base_data.ok.unwrap(), 1);
154    }
155
156    #[tokio::test]
157    async fn test_get_my_name() {
158        let api = screeps_api_from_env!().unwrap();
159        let my_name = api.get_my_name().await.unwrap();
160        assert_eq!(my_name.base_data.ok.unwrap(), 1);
161    }
162
163    #[tokio::test]
164    async fn test_get_user_info_by_id() {
165        let api = screeps_api_from_env!().unwrap();
166        let user_info = api
167            .get_user_info_by_id("61f26f882181b7ba48c7015c")
168            .await
169            .unwrap();
170        assert_eq!(user_info.base_data.ok.unwrap(), 1);
171    }
172
173    #[tokio::test]
174    async fn test_get_user_info_by_name() {
175        let api = ScreepsApi::new(ScreepsConfig::default());
176        let user_info = api.get_user_info_by_name("keqing").await.unwrap();
177        assert_eq!(user_info.base_data.ok.unwrap(), 1);
178    }
179
180    #[tokio::test]
181    async fn test_get_user_rooms() {
182        let api = ScreepsApi::default();
183        let user_rooms = api
184            .get_user_rooms("61f26f882181b7ba48c7015c")
185            .await
186            .unwrap();
187        assert_eq!(user_rooms.base_data.ok.unwrap(), 1);
188    }
189
190    #[tokio::test]
191    async fn test_get_room_objects() {
192        let api = ScreepsApi::default();
193        let room_objects = api.get_room_objects("E13S13", "shard3").await;
194        match room_objects {
195            Ok(room_objects) => {
196                assert_eq!(room_objects.base_data.ok.unwrap(), 1);
197            }
198            Err(err) => panic!("{}", err),
199        }
200    }
201
202    #[tokio::test]
203    async fn test_get_room_terrain() {
204        let api = ScreepsApi::default();
205        let room_terrain = api.get_room_terrain("E21N19", "shard0").await.unwrap();
206        assert_eq!(room_terrain.base_data.ok.unwrap(), 1);
207    }
208
209    #[tokio::test]
210    async fn test_get_room_terrain_encoded() {
211        let api = ScreepsApi::default();
212        let room_terrain_encoded = api
213            .get_room_terrain_encoded("E13S13", "shard3")
214            .await
215            .unwrap();
216        assert_eq!(room_terrain_encoded.base_data.ok.unwrap(), 1);
217    }
218
219    #[tokio::test]
220    async fn test_get_room_status() {
221        let api = screeps_api_from_env!().unwrap();
222        let room_status = api.get_room_status("E13S13", "shard3").await.unwrap();
223        assert_eq!(room_status.base_data.ok.unwrap(), 1);
224    }
225
226    #[tokio::test]
227    async fn test_get_shards() {
228        let api = ScreepsApi::default();
229        let my_info = api.get_shards().await.unwrap();
230        assert_eq!(my_info.base_data.ok.unwrap(), 1);
231    }
232
233    #[tokio::test]
234    async fn test_get_shard_time() {
235        let api = ScreepsApi::default();
236        let game_time = api.get_shard_time("shard3").await.unwrap();
237        assert_eq!(game_time.base_data.ok.unwrap(), 1);
238    }
239}