Made server and client 1
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
use warp::Filter;
|
||||
use crate::
|
||||
{
|
||||
// internal code
|
||||
character,
|
||||
// libraries
|
||||
HashMap,
|
||||
Arc,
|
||||
Mutex,
|
||||
config,
|
||||
mpsc::Sender,
|
||||
info,
|
||||
debug,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct DataToSend {
|
||||
pub action_type: String,
|
||||
pub content: String,
|
||||
pub character: String,
|
||||
pub choices: Vec<String>,
|
||||
}
|
||||
|
||||
// Async function that runs the api server in the background.
|
||||
// Waits for the client to load it, at which point it sends a 1 over
|
||||
// tx to allow the program executor to move onto the next bit of code
|
||||
pub async fn api_process
|
||||
(
|
||||
data_to_send: Arc<Mutex<DataToSend>>,
|
||||
characters: Arc<Mutex<HashMap::<String,character::Character>>>,
|
||||
tx: Sender<(bool, usize)>,
|
||||
)
|
||||
{
|
||||
// This data must be passed through to the api route in order to be used
|
||||
let data_filter = warp::any().map(move || Arc::clone(&data_to_send));
|
||||
let characters_filter = warp::any().map(move || Arc::clone(&characters));
|
||||
let tx_filter = warp::any().map(move || tx.clone());
|
||||
let tx_filter2 = tx_filter.clone();
|
||||
|
||||
info!("Running server");
|
||||
|
||||
// The server route is loaded at address:port/happening
|
||||
let main = warp::path("happening")
|
||||
.and(warp::get())
|
||||
.and(data_filter)
|
||||
.and(tx_filter)
|
||||
// Perform this code on a GET request
|
||||
.map(|state: Arc<Mutex<DataToSend>>, tx_handle: Sender<(bool,usize)>|
|
||||
{
|
||||
info!("GET: {:?}", state);
|
||||
let reply = state.as_ref();
|
||||
let _ = tx_handle.send((true,0));
|
||||
warp::reply::json(&reply) // Send the reply data (data_to_send formatted as JSON)
|
||||
}).boxed();
|
||||
let characters = warp::path("character")
|
||||
.and(warp::get())
|
||||
.and(warp::path::param::<String>())
|
||||
.and(characters_filter)
|
||||
.map(|name: String, characters: Arc<Mutex<HashMap<String, character::Character>>>|
|
||||
{
|
||||
let map = characters.lock().unwrap(); // TODO remove unwrap
|
||||
let reply = map.get(&name).unwrap();
|
||||
debug!("GET: name: {}", name);
|
||||
warp::reply::json(&reply)
|
||||
}).boxed();
|
||||
let choice = warp::path("choice")
|
||||
.and(warp::post())
|
||||
.and(warp::body::json())
|
||||
.and(tx_filter2)
|
||||
.map(|index: usize, tx_handle: Sender<(bool,usize)>| {
|
||||
debug!("Choice: {}", index);
|
||||
let _ = tx_handle.send((true,index));
|
||||
let reply = "ack";
|
||||
warp::reply::json(&reply)
|
||||
}).boxed();
|
||||
|
||||
let routes = main.or(characters).or(choice);
|
||||
// Start the server
|
||||
warp::serve(routes)
|
||||
.run(([127, 0, 0, 1],config::API_PORT))
|
||||
.await;
|
||||
}
|
||||
Reference in New Issue
Block a user