Created
August 19, 2020 03:46
-
-
Save Fyko/eb5ceb511e134d31f5bc024eb8e809fa to your computer and use it in GitHub Desktop.
client for interacting with https://github.com/spec-tacles/proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate log; | |
use anyhow::Result; | |
use rustacles_brokers::amqp::AmqpBroker; | |
use serde_json::{from_slice, to_vec}; | |
use std::collections::HashMap; | |
use tokio::time::{delay_for, timeout, Duration}; | |
pub use proxy::models::*; | |
pub use serde_json::*; | |
pub struct Rest { | |
pub broker: AmqpBroker, | |
pub default_headers: HashMap<String, String>, | |
options: RestOptions, | |
} | |
pub struct RestOptions { | |
amqp_event: String, | |
amqp_url: String, | |
amqp_group: String, | |
amqp_subgroup: Option<String>, | |
discord_token: String, | |
} | |
impl Rest { | |
pub async fn new(options: RestOptions) -> Self { | |
let mut default_headers = HashMap::new(); | |
default_headers.insert("Content-Type".to_owned(), "application/json".to_owned()); | |
default_headers.insert( | |
"Authorization".to_owned(), | |
format!("Bot {}", options.discord_token), | |
); | |
default_headers.insert("X-RateLimit-Precision".to_owned(), "millisecond".to_owned()); | |
let broker: AmqpBroker = loop { | |
let broker_res = AmqpBroker::new( | |
&options.amqp_url, | |
options.amqp_group.clone(), | |
options.amqp_subgroup.clone(), | |
) | |
.await; | |
if let Ok(b) = broker_res { | |
break b.with_rpc().await.unwrap(); | |
} else { | |
error!( | |
"Error when connecting to the broker: {:#?}", | |
broker_res.err() | |
) | |
} | |
delay_for(Duration::from_secs(5)).await; | |
}; | |
Self { | |
broker, | |
default_headers, | |
options | |
} | |
} | |
pub async fn request(&self, payload: SerializableHttpRequest) -> Result<RequestResponse<SerializableHttpResponse>> { | |
let response = timeout( | |
Duration::from_secs(5), | |
self.broker.call( | |
&self.options.amqp_event, | |
to_vec(&payload).unwrap(), | |
Default::default(), | |
), | |
) | |
.await.unwrap().unwrap(); | |
let response: Result<RequestResponse<SerializableHttpResponse>, _> = | |
from_slice(&response.data); | |
match response { | |
Ok(response) => Ok(response), | |
Err(err) => Err(anyhow::anyhow!(err)) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment