1use anyhow::{Context, Result, anyhow};
2use serde_json::{Value, json};
3
4use super::client::DiscourseClient;
5use super::error::http_error;
6
7impl DiscourseClient {
8 pub fn list_themes(&self) -> Result<Value> {
10 let response = self.get("/admin/themes.json")?;
11 let status = response.status();
12 let text = response.text().context("reading themes response body")?;
13 if !status.is_success() {
14 return Err(http_error("themes request", status, &text));
15 }
16 let value: Value = serde_json::from_str(&text).context("parsing themes response")?;
17 Ok(value)
18 }
19
20 pub fn fetch_theme(&self, theme_id: u64) -> Result<Value> {
22 let response = self.get(&format!("/admin/themes/{}.json", theme_id))?;
23 let status = response.status();
24 let text = response.text().context("reading theme response body")?;
25 if !status.is_success() {
26 return Err(http_error("theme request", status, &text));
27 }
28 let value: Value = serde_json::from_str(&text).context("parsing theme response")?;
29 Ok(value)
30 }
31
32 pub fn create_theme(&self, theme: &Value) -> Result<u64> {
34 let payload = json!({ "theme": theme });
35 let response = self.send_retrying(|| Ok(self.post("/admin/themes.json")?.json(&payload)))?;
36 let status = response.status();
37 let text = response.text().context("reading create theme response")?;
38 if !status.is_success() {
39 return Err(http_error("create theme request", status, &text));
40 }
41 let value: Value =
42 serde_json::from_str(&text).context("parsing create theme response")?;
43 let id = value
44 .get("theme")
45 .and_then(|v| v.get("id"))
46 .or_else(|| value.get("id"))
47 .and_then(|v| v.as_u64())
48 .ok_or_else(|| anyhow!("missing theme id in create response"))?;
49 Ok(id)
50 }
51
52 pub fn delete_theme(&self, theme_id: u64) -> Result<()> {
54 let response = self.delete(&format!("/admin/themes/{}.json", theme_id))?;
55 let status = response.status();
56 let text = response.text().context("reading delete theme response")?;
57 if !status.is_success() {
58 return Err(http_error("delete theme request", status, &text));
59 }
60 Ok(())
61 }
62
63 pub fn update_theme(&self, theme_id: u64, theme: &Value) -> Result<()> {
65 let payload = json!({ "theme": theme });
66 let path = format!("/admin/themes/{}.json", theme_id);
67 let response = self.send_retrying(|| Ok(self.put(&path)?.json(&payload)))?;
68 let status = response.status();
69 let text = response.text().context("reading update theme response")?;
70 if !status.is_success() {
71 return Err(http_error("update theme request", status, &text));
72 }
73 Ok(())
74 }
75}