mangadex_api/v5/report/
post.rs

1//! Builder for creating a new report.
2//!
3//! <https://api.mangadex.org/docs/swagger.html#/Report/post-report>
4//!
5//! # Examples
6//!
7//! ```rust
8//! use uuid::Uuid;
9//!
10//! use mangadex_api_types::ReportCategory;
11//! use mangadex_api::MangaDexClient;
12//! // use mangadex_api_types::{Password, Username};
13//!
14//! # async fn run() -> anyhow::Result<()> {
15//! let client = MangaDexClient::default();
16//!
17//! /*
18//!
19//!     let _login_res = client
20//!         .auth()
21//!         .login()
22//!         .post()
23//!         .username(Username::parse("myusername")?)
24//!         .password(Password::parse("hunter23")?)
25//!         .send()
26//!         .await?;
27//!
28//!  */
29//!
30//!
31//! let reason_id = Uuid::new_v4();
32//! let manga_id = Uuid::new_v4();
33//!
34//! let res = client
35//!     .report()
36//!     .post()
37//!     .category(ReportCategory::Manga)
38//!     .reason(reason_id)
39//!     .object_id(manga_id)
40//!     .send()
41//!     .await?;
42//!
43//! println!("report reasons: {:?}", res);
44//! # Ok(())
45//! # }
46//! ```
47
48use derive_builder::Builder;
49use serde::Serialize;
50use uuid::Uuid;
51
52use crate::HttpClientRef;
53use mangadex_api_schema::NoData;
54use mangadex_api_types::ReportCategory;
55
56#[cfg_attr(
57    feature = "deserializable-endpoint",
58    derive(serde::Deserialize, getset::Getters, getset::Setters)
59)]
60#[derive(Debug, Serialize, Clone, Builder)]
61#[serde(rename_all = "camelCase")]
62#[builder(
63    setter(into, strip_option),
64    build_fn(error = "crate::error::BuilderError")
65)]
66#[non_exhaustive]
67pub struct CreateReport {
68    #[doc(hidden)]
69    #[serde(skip)]
70    #[builder(pattern = "immutable")]
71    #[cfg_attr(feature = "deserializable-endpoint", getset(set = "pub", get = "pub"))]
72    pub http_client: HttpClientRef,
73
74    pub category: ReportCategory,
75    /// The report reason ID for sub-categorization.
76    ///
77    /// For example, if a manga was being reported for being a troll entry, the specific reason ID should be used, obtained from the [list report reasons endpoint](crate::v5::report::get).
78    pub reason: Uuid,
79    /// The ID from the category type.
80    ///
81    /// For example, if the category is "manga", this should be a manga UUID.
82    pub object_id: Uuid,
83    /// Optional notes about why this is being reported.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    #[builder(default)]
86    pub details: Option<String>,
87}
88
89endpoint! {
90    POST "/report",
91    #[body auth] CreateReport,
92    #[rate_limited] NoData,
93    CreateReportBuilder
94}
95
96#[cfg(test)]
97mod tests {
98    use serde_json::json;
99    use url::Url;
100    use uuid::Uuid;
101    use wiremock::matchers::{body_json, header, method, path};
102    use wiremock::{Mock, MockServer, ResponseTemplate};
103
104    use crate::v5::AuthTokens;
105    use crate::{HttpClient, MangaDexClient};
106    use mangadex_api_types::ReportCategory;
107
108    #[tokio::test]
109    async fn create_report_reasons_fires_a_request_to_base_url() -> anyhow::Result<()> {
110        let mock_server = MockServer::start().await;
111        let http_client = HttpClient::builder()
112            .base_url(Url::parse(&mock_server.uri())?)
113            .auth_tokens(non_exhaustive::non_exhaustive!(AuthTokens {
114                session: "sessiontoken".to_string(),
115                refresh: "refreshtoken".to_string(),
116            }))
117            .build()?;
118        let mangadex_client = MangaDexClient::new_with_http_client(http_client);
119
120        let reason_id = Uuid::new_v4();
121        let manga_id = Uuid::new_v4();
122        let expected_body = json!({
123            "category": "manga",
124            "reason": reason_id,
125            "objectId": manga_id,
126        });
127        let response_body = json!({
128            "result": "ok"
129        });
130
131        Mock::given(method("POST"))
132            .and(path("/report"))
133            .and(header("Authorization", "Bearer sessiontoken"))
134            .and(header("Content-Type", "application/json"))
135            .and(body_json(expected_body))
136            .respond_with(
137                ResponseTemplate::new(200)
138                    .insert_header("x-ratelimit-retry-after", "1698723860")
139                    .insert_header("x-ratelimit-limit", "40")
140                    .insert_header("x-ratelimit-remaining", "39")
141                    .set_body_json(response_body),
142            )
143            .expect(1)
144            .mount(&mock_server)
145            .await;
146
147        mangadex_client
148            .report()
149            .post()
150            .category(ReportCategory::Manga)
151            .reason(reason_id)
152            .object_id(manga_id)
153            .send()
154            .await?;
155
156        Ok(())
157    }
158}