use serde::{Deserialize, Serialize};
use serde_json::{value::Index, Value};
use std::fmt;
pub(crate) use body::Body;
pub use builder::ApiBuilder;
pub mod private;
pub mod public;
mod body;
mod builder;
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct Response<T> {
pub error: Vec<String>,
pub result: Option<T>,
#[serde(skip)]
pub status_code: u16,
}
pub type ResponseValue = Response<Value>;
impl ResponseValue {
pub fn get(&self, index: impl Index) -> Option<&Value> {
self.result.as_ref().and_then(|r| r.get(index))
}
pub fn get_mut(&mut self, index: impl Index) -> Option<&mut Value> {
self.result.as_mut().and_then(|r| r.get_mut(index))
}
}
impl<T> Response<T> {
pub fn is_success(&self) -> bool {
self.error.is_empty()
&& self.status_code >= 200
&& self.status_code < 300
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Api {
pub(crate) inner: ApiBuilder,
}
impl Api {
pub fn is_public(&self) -> bool {
self.inner.kind == ApiKind::Public
}
pub fn is_private(&self) -> bool {
self.inner.kind == ApiKind::Private
}
pub fn url(&self) -> String {
self.inner.url()
}
}
impl From<ApiBuilder> for Api {
fn from(inner: ApiBuilder) -> Self {
Self { inner }
}
}
impl fmt::Display for Api {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inner)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ApiKind {
Public,
Private,
}
impl fmt::Display for ApiKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Public => write!(f, "public"),
Self::Private => write!(f, "private"),
}
}
}