use crate::{graphql, Opt};
use log::{error, info};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Input {
id: usize,
payload: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Output {
id: usize,
payload: String,
}
pub async fn run(_opt: Opt) {
let schema = graphql::new_schema();
info!("Monitoring stdin...");
let stdin = std::io::stdin();
let mut buffer = String::new();
loop {
let result = stdin.read_line(&mut buffer);
match result {
Ok(n) if n > 0 => {
if let Ok(Input { id, payload }) = serde_json::from_str(&buffer)
{
let response = schema.execute(&payload).await;
send_response(id, response).await;
}
buffer.clear();
}
Ok(_) => break,
Err(x) => {
error!("Failed to read stdin: {}", x);
break;
}
}
}
}
async fn send_response(id: usize, response: async_graphql::Response) {
match serde_json::to_string(&response)
.map(|payload| Output { id, payload })
.and_then(|output| serde_json::to_string(&output))
{
Ok(msg) => println!("{}", msg),
Err(x) => eprintln!("{}", x),
}
}