Skip to main content

fishpi_sdk/api/
comment.rs

1//! 评论 API 模块
2//!
3//! 这个模块提供了与评论相关的 API 操作,包括发布评论、更新评论、点赞评论、感谢评论、删除评论等功能。
4//! 主要结构体是 `Comment`,用于管理评论的 API 请求。
5//!
6//! # 主要组件
7//!
8//! - [`Comment`] - 评论客户端结构体,负责所有评论相关的 API 调用。
9//!
10//! # 方法列表
11//!
12//! - [`Comment::new`] - 创建新的评论客户端实例。
13//! - [`Comment::send`] - 发布评论。
14//! - [`Comment::update`] - 更新评论。
15//! - [`Comment::vote`] - 评论点赞。
16//! - [`Comment::thank`] - 评论感谢。
17//! - [`Comment::remove`] - 删除评论。
18//!
19//! # 示例
20//!
21//! ```rust,no_run
22//! use fishpi_sdk::api::comment::Comment;
23//! use fishpi_sdk::model::article::CommentPost;
24//!
25//! #[tokio::main]
26//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
27//!     let comment = Comment::new("your_api_key".to_string());
28//!
29//!     // 发布评论
30//!     let data = CommentPost {
31//!         articleId: "article_id".to_string(),
32//!         isAnonymous: false,
33//!         isVisible: true,
34//!         content: "This is a comment.".to_string(),
35//!         replyId: "".to_string(),
36//!     };
37//!     let result = comment.send(&data).await?;
38//!     println!("Sent: {}", result.success);
39//!
40//!     // 更新评论
41//!     let updated_content = comment.update("comment_id", &data).await?;
42//!     println!("Updated content: {}", updated_content);
43//!
44//!     // 点赞评论
45//!     let voted = comment.vote("comment_id", true).await?;
46//!     println!("Voted: {}", voted);
47//!
48//!     Ok(())
49//! }
50//! ```
51use serde_json::{Value, json};
52
53use crate::{
54    model::article::CommentPost,
55    utils::{ResponseResult, error::Error, post, put},
56};
57
58pub struct Comment {
59    api_key: String,
60}
61
62impl Comment {
63    pub fn new(api_key: String) -> Self {
64        Self { api_key }
65    }
66
67    /// 发布评论
68    ///
69    /// - `data` 评论信息
70    ///
71    /// 返回执行结果
72    pub async fn send(&self, data: &CommentPost) -> Result<ResponseResult, Error> {
73        let url = "comment".to_string();
74
75        let mut data_json = data.to_value()?;
76        data_json["apiKey"] = Value::String(self.api_key.clone());
77
78        let rsp = post(&url, Some(data_json)).await?;
79
80        ResponseResult::from_value(&rsp)
81    }
82
83    /// 更新评论
84    ///
85    /// - `id` 评论 Id
86    /// - `data` 评论信息
87    ///
88    /// 返回评论内容 HTML
89    pub async fn update(&self, id: &str, data: &CommentPost) -> Result<String, Error> {
90        let url = format!("comment/{}", id);
91
92        let mut data_json = data.to_value()?;
93        data_json["apiKey"] = Value::String(self.api_key.clone());
94
95        let rsp = put(&url, Some(data_json)).await?;
96
97        if rsp.get("code").and_then(|c| c.as_i64()).unwrap_or(-1) != 0 {
98            return Err(Error::Api(
99                rsp["msg"].as_str().unwrap_or("API error").to_string(),
100            ));
101        }
102
103        Ok(rsp["commentContent"].as_str().unwrap_or("").to_string())
104    }
105
106    /// 评论点赞
107    ///
108    /// - `id` 评论 Id
109    /// - `like` 点赞类型,true 为点赞,false 为点踩
110    ///
111    /// 返回评论点赞状态,true 为点赞,false 为点踩
112    pub async fn vote(&self, id: &str, like: bool) -> Result<bool, Error> {
113        let action = if like { "up" } else { "down" };
114        let url = format!("vote/{}/comment", action);
115
116        let data_json = json!({
117            "dataId": id,
118            "apiKey": self.api_key,
119        });
120
121        let rsp = post(&url, Some(data_json)).await?;
122
123        if rsp.get("code").and_then(|c| c.as_i64()).unwrap_or(-1) != 0 {
124            return Err(Error::Api(
125                rsp["msg"].as_str().unwrap_or("API error").to_string(),
126            ));
127        }
128
129        Ok(rsp["type"].as_i64().unwrap_or(-1) == 0)
130    }
131
132    /// 评论感谢
133    ///
134    /// - `id` 评论 Id
135    ///
136    /// 返回执行结果
137    pub async fn thank(&self, id: &str) -> Result<ResponseResult, Error> {
138        let url = "comment/thank".to_string();
139
140        let data_json = json!({
141            "apiKey": self.api_key,
142            "commentId": id,
143        });
144
145        let rsp = post(&url, Some(data_json)).await?;
146
147        ResponseResult::from_value(&rsp)
148    }
149
150    /// 删除评论
151    ///
152    /// - `id` 评论 Id
153    ///
154    /// 返回删除的评论 Id
155    pub async fn remove(&self, id: &str) -> Result<String, Error> {
156        let url = format!("comment/{}/remove", id);
157
158        let data_json = json!({
159            "apiKey": self.api_key,
160        });
161
162        let rsp = post(&url, Some(data_json)).await?;
163
164        if rsp.get("code").and_then(|c| c.as_i64()).unwrap_or(-1) != 0 {
165            return Err(Error::Api(
166                rsp["msg"].as_str().unwrap_or("API error").to_string(),
167            ));
168        }
169
170        Ok(rsp["commentId"].as_str().unwrap_or("").to_string())
171    }
172}