markdown.rs 2.17 KB
use std::fmt::Display;

use artshop_common::types::MarkdownJson;

use super::super::error::*;
use super::super::client::Client;

#[derive(Debug, Clone)]
pub struct Markdown {
    client: Client,
    pub json: MarkdownJson,
}

impl Markdown {
    pub(crate) async fn new(name :&str) -> Result<Markdown> {
        let client = Client::new()?;
        let api_uri = format!("/api/v0/markdowns/{}", name);
        let (response, data) = client.get(&api_uri).await?;

        match response.status() {
            200 => Ok(Self { client
                           , json: serde_json::from_str(data.as_str())? }),
            status => Err(Self::status_error(status)),
        }
    }

    pub(crate) async fn read( &mut self
                            , patch :Option<i32>
                            ) -> Result<&Markdown>
    {
        let api_uri = match patch {
            Some(i) => format!( "/api/v0/markdowns/{}?patch={}"
                              , self.json.name, i ),
            None    => format!("/api/v0/markdowns/{}", self.json.name),
        };
        let (response, data) = self.client.get(&api_uri).await?;

        match response.status() {
            200 => {
                self.json = serde_json::from_str(data.as_str())?;
                Ok(self)
            },
            status => Err(Self::status_error(status)),
        }
    }

    pub(crate) async fn save(&self) -> Result<&Markdown> {
        let url = format!("/api/v0/markdowns/{}", self.json.name);
        let data = serde_json::to_string(&self.json)?;

        let response = self.client.put(url.as_str(), data.as_str()).await?;

        match response.status() {
            200 => Ok(self),
            status => Err(Self::status_error(status)),
        }
    }

    pub(crate) fn _to_html_string(&self) -> String {
        use pulldown_cmark::{Parser, Options, html};

        let mut html_out = String::new();
        let parser = Parser::new_ext(&self.json.content, Options::all());

        html::push_html(&mut html_out, parser);
        html_out
    }


    fn status_error<I: Display>(status :I) -> Error {
        let err_str = format!("Invalid response status: {}", status);
        Error::from(err_str.as_str())
    }
}