use crate::client::http::MOST_IN_BATCH;
use crate::live::Subscription;
use crate::utils::Json;
use crate::utils::json::BadJson;
pub const PING: &str = r#"{"type":"ping"}"#;
pub const PONG: &str = r#"{"type":"pong"}"#;
#[must_use]
pub fn subscribe(subscription: &Subscription, auth: Option<&str>) -> String {
let mut fields = vec![text("type", "subscribe"), text("channel", &subscription.channel())];
if let Some(token) = auth.filter(|_| subscription.takes_auth()) {
fields.push(text("auth", token));
}
Json::Object(fields).compact()
}
#[must_use]
pub fn unsubscribe(subscription: &Subscription) -> String {
Json::Object(vec![text("type", "unsubscribe"), text("channel", &subscription.channel())]).compact()
}
#[must_use]
pub fn resubscribe(subscription: &Subscription, auth: Option<&str>) -> [String; 2] {
[unsubscribe(subscription), subscribe(subscription, auth)]
}
pub fn send_tx(id: &str, tx_type: u8, tx_info: &str) -> Result<String, BadJson> {
let info = Json::parse(tx_info)?;
let data = Json::Object(vec![
text("id", id),
("tx_type".to_owned(), Json::Number(tx_type.to_string())),
("tx_info".to_owned(), info),
]);
Ok(Json::Object(vec![text("type", "jsonapi/sendtx"), ("data".to_owned(), data)]).compact())
}
#[must_use]
pub fn send_tx_batch(id: &str, txs: &[(u8, String)]) -> String {
let types = Json::Array(txs.iter().map(|(tx_type, _)| Json::Number(tx_type.to_string())).collect());
let infos = Json::Array(txs.iter().map(|(_, info)| Json::String(info.clone())).collect());
let data =
Json::Object(vec![text("id", id), text("tx_types", &types.compact()), text("tx_infos", &infos.compact())]);
Json::Object(vec![text("type", "jsonapi/sendtxbatch"), ("data".to_owned(), data)]).compact()
}
#[must_use]
pub const fn batch_fits(count: usize) -> bool {
count >= 1 && count <= MOST_IN_BATCH
}
fn text(key: &str, value: &str) -> (String, Json) {
(key.to_owned(), Json::String(value.to_owned()))
}
#[cfg(test)]
#[path = "tests/request.rs"]
mod tests;