algonaut_algod 0.9.0

API endpoint for algod operations.
Documentation
use std::error;
use std::fmt;

#[derive(Debug, Clone)]
pub struct ResponseContent<T> {
    pub status: reqwest::StatusCode,
    pub content: String,
    pub entity: Option<T>,
}

#[derive(Debug)]
pub enum Error<T> {
    Reqwest(reqwest::Error),
    Serde(serde_json::Error),
    Msgpack(rmp_serde::decode::Error),
    Io(std::io::Error),
    ResponseError(ResponseContent<T>),
}

impl<T> fmt::Display for Error<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (module, e) = match self {
            Error::Reqwest(e) => ("reqwest", e.to_string()),
            Error::Serde(e) => ("serde", e.to_string()),
            Error::Msgpack(e) => ("msgpack", e.to_string()),
            Error::Io(e) => ("IO", e.to_string()),
            Error::ResponseError(e) => ("response", format!("status code {}", e.status)),
        };
        write!(f, "error in {}: {}", module, e)
    }
}

impl<T: fmt::Debug> error::Error for Error<T> {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(match self {
            Error::Reqwest(e) => e,
            Error::Serde(e) => e,
            Error::Msgpack(e) => e,
            Error::Io(e) => e,
            Error::ResponseError(_) => return None,
        })
    }
}

impl<T> From<reqwest::Error> for Error<T> {
    fn from(e: reqwest::Error) -> Self {
        Error::Reqwest(e)
    }
}

impl<T> From<serde_json::Error> for Error<T> {
    fn from(e: serde_json::Error) -> Self {
        Error::Serde(e)
    }
}

impl<T> From<rmp_serde::decode::Error> for Error<T> {
    fn from(e: rmp_serde::decode::Error) -> Self {
        Error::Msgpack(e)
    }
}

impl<T> From<std::io::Error> for Error<T> {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

pub fn urlencode<T: AsRef<str>>(s: T) -> String {
    ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect()
}

/// Decode a successful response body into a typed model, negotiating the
/// wire format from the response `Content-Type`.
///
/// algod can answer with either JSON or msgpack (the latter when the request
/// carried `format=msgpack`). msgpack response bodies use the same top-level
/// field names as the generated models' `#[serde(rename = "...")]`, so the
/// model deserializes from either format unchanged — only the decoder differs.
///
/// `application/msgpack` (matched case-insensitively, ignoring any `;`-suffixed
/// parameters) is decoded with `rmp_serde`; anything else is decoded as JSON.
pub fn decode_response_body<T, E>(content_type: Option<&str>, body: &[u8]) -> Result<T, Error<E>>
where
    T: serde::de::DeserializeOwned,
{
    let is_msgpack = content_type
        .map(|ct| {
            ct.split(';')
                .next()
                .unwrap_or(ct)
                .trim()
                .eq_ignore_ascii_case("application/msgpack")
        })
        .unwrap_or(false);

    if is_msgpack {
        rmp_serde::from_slice(body).map_err(Error::from)
    } else {
        serde_json::from_slice(body).map_err(Error::from)
    }
}

pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> {
    if let serde_json::Value::Object(object) = value {
        let mut params = vec![];

        for (key, value) in object {
            match value {
                serde_json::Value::Object(_) => params.append(&mut parse_deep_object(
                    &format!("{}[{}]", prefix, key),
                    value,
                )),
                serde_json::Value::Array(array) => {
                    for (i, value) in array.iter().enumerate() {
                        params.append(&mut parse_deep_object(
                            &format!("{}[{}][{}]", prefix, key, i),
                            value,
                        ));
                    }
                }
                serde_json::Value::String(s) => {
                    params.push((format!("{}[{}]", prefix, key), s.clone()))
                }
                _ => params.push((format!("{}[{}]", prefix, key), value.to_string())),
            }
        }

        return params;
    }

    unimplemented!("Only objects are supported with style=deepObject")
}

pub mod common_api;
pub mod data_api;
pub mod experimental_api;
pub mod nonparticipating_api;
pub mod participating_api;
pub mod private_api;
pub mod public_api;

pub mod configuration;