-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.rs
More file actions
73 lines (64 loc) · 2.09 KB
/
server.rs
File metadata and controls
73 lines (64 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
mod context;
mod handler;
mod state;
use crate::error::MocksError;
use crate::server::handler::delete::delete;
use crate::server::handler::get::{get_all, get_one};
use crate::server::handler::hc::hc;
use crate::server::handler::patch::{patch, patch_one};
use crate::server::handler::post::post;
use crate::server::handler::put::{put, put_one};
use crate::server::state::{AppState, SharedState};
use crate::storage::Storage;
use axum::routing::get;
use axum::Router;
use serde_json::Value;
use std::net::SocketAddr;
use tokio::net::TcpListener;
/// Mock server module
pub struct Server {}
impl Server {
/// Starts the mock server
///
/// # Arguments
/// * `socket_addr` - The socket address to bind the server to
/// * `url` - The base URL of the server
/// * `storage` - The storage instance to use
///
/// # Returns
/// * `Result<(), MocksError>` - Ok if the server starts successfully, Err otherwise
pub async fn startup(
socket_addr: SocketAddr,
url: &str,
storage: Storage,
) -> Result<(), MocksError> {
let listener = TcpListener::bind(socket_addr)
.await
.map_err(|e| MocksError::Exception(e.to_string()))?;
println!("Endpoints:");
print_endpoints(url, &storage.data);
let state = AppState::new(storage);
let router = create_router(state);
axum::serve(listener, router)
.await
.map_err(|e| MocksError::Exception(e.to_string()))
}
}
fn print_endpoints(url: &str, value: &Value) {
println!("{}/_hc", url);
if let Value::Object(obj) = value {
for (key, _) in obj {
println!("{}/{}", url, key);
}
}
}
fn create_router(state: SharedState) -> Router {
let hc_router = Router::new().route("/", get(hc));
let storage_router = Router::new()
.route("/", get(get_all).post(post).put(put_one).patch(patch_one))
.route("/:id", get(get_one).put(put).patch(patch).delete(delete));
Router::new()
.nest("/_hc", hc_router)
.nest("/:resource", storage_router)
.with_state(state)
}