markdown.rs
2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::fmt::Display;
use artshop_common::types::{MarkdownJson, MarkdownDiffJson};
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) async fn patches(&self) -> Result<Vec<MarkdownDiffJson>> {
let url = format!("/api/v0/markdowns/{}/patches", self.json.name);
let (response, data) = self.client.get(url.as_str()).await?;
match response.status() {
200 => Ok(serde_json::from_str(&data)?),
status => Err(Self::status_error(status)),
}
}
fn status_error<I: Display>(status :I) -> Error {
let err_str = format!("Invalid response status: {}", status);
Error::from(err_str.as_str())
}
}