use anyhow::Result;
use serde::Deserialize;
use thiserror::Error;
use crate::TelegramClient;
#[derive(Error, Debug)]
pub enum ApiError {
#[error("Telegram error: {0}")]
AppError(String),
#[error("Client error: {0}")]
ClientError(String),
#[error("No result")]
NoResult,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ApiResponse<T> {
pub ok: bool,
pub description: Option<String>,
pub result: Option<T>,
}
#[allow(clippy::should_implement_trait)]
impl<'de, T: Deserialize<'de>> ApiResponse<T> {
pub fn from_str(data: &'de str) -> Result<Self> {
let response: ApiResponse<T> = serde_json::from_str(data)?;
Ok(response)
}
}
impl<T> ApiResponse<T> {
pub fn is_ok(&self) -> bool {
self.ok
}
pub fn result(&self) -> Result<&T> {
if !self.ok {
return Err(ApiError::AppError(
self.description
.clone()
.unwrap_or("No error description".to_string()),
)
.into());
}
if self.result.is_none() {
return Err(ApiError::NoResult.into());
}
Ok(self.result.as_ref().unwrap())
}
}
#[derive(Debug)]
pub struct API<T: TelegramClient> {
pub client: T,
}
impl<T: TelegramClient> API<T> {
pub fn new(client: T) -> Self {
Self { client }
}
}