use crate::error::*;
use crate::raw;
use crate::Napchart;
use serde::Deserialize;
use std::convert::{TryFrom, TryInto};
#[derive(Deserialize)]
struct CreateResponse {
chartid: String,
}
#[cfg(feature = "async")]
pub struct AsyncClient {
internal: reqwest::Client,
}
#[cfg(feature = "async")]
impl AsyncClient {
pub async fn get<'a, T: Into<&'a str>>(&self, chartid: T) -> Result<Napchart> {
self.internal
.get(format!(
"https://thumb.napchart.com/api/get?chartid={}",
chartid.into()
))
.send()
.await?
.json::<raw::Napchart>()
.await?
.try_into()
}
pub async fn create(&self, chart: &Napchart) -> Result<String> {
Ok(self
.internal
.post("https://thumb.napchart.com/alt/api/create")
.json(&raw::Napchart::try_from(chart.clone())?.as_uploadable())
.send()
.await?
.json::<CreateResponse>()
.await?
.chartid)
}
pub async fn create_new(&self, chart: &mut Napchart) -> Result<()> {
chart.chartid = Some(self.create(chart).await?);
Ok(())
}
}
#[cfg(feature = "async")]
impl Default for AsyncClient {
fn default() -> Self {
Self {
internal: reqwest::Client::new(),
}
}
}
#[cfg(feature = "blocking")]
pub struct BlockingClient {
internal: reqwest::blocking::Client,
}
impl BlockingClient {
pub fn get<'a, T: Into<&'a str>>(&self, chartid: T) -> Result<Napchart> {
self.internal
.get(format!(
"https://thumb.napchart.com/api/get?chartid={}",
chartid.into()
))
.send()?
.json::<raw::Napchart>()?
.try_into()
}
pub fn create(&self, chart: &Napchart) -> Result<String> {
Ok(self
.internal
.post("https://thumb.napchart.com/alt/api/create")
.json(&raw::Napchart::try_from(chart.clone())?.as_uploadable())
.send()?
.json::<CreateResponse>()?
.chartid)
}
pub fn create_new(&self, chart: &mut Napchart) -> Result<()> {
chart.chartid = Some(self.create(chart)?);
Ok(())
}
}
impl Default for BlockingClient {
fn default() -> Self {
BlockingClient {
internal: reqwest::blocking::Client::new(),
}
}
}