Skip to main content

acosmi/notifications/
notifications.rs

1//! 通知业务方法。端口自 `notifications/notifications.ts`
2//! (declaration-merging → 此处 `impl Client` 块)。
3
4use super::types::{
5    DeviceRegistration, NotificationList, NotificationPreference, NotificationUnreadCount,
6};
7use crate::billing::entitlements::urlencoding;
8use crate::core::client::Client;
9use crate::core::http::DEFAULT_JSON_TIMEOUT_MS;
10use crate::shared::{ApiResponse, Error, Result};
11use tokio_util::sync::CancellationToken;
12
13impl Client {
14    /// 分页查询通知列表。对应 TS `listNotifications`。
15    pub async fn list_notifications(
16        &self,
17        page: i64,
18        page_size: i64,
19        type_filter: &str,
20        signal: Option<CancellationToken>,
21    ) -> Result<NotificationList> {
22        let mut path = format!("/notifications?page={page}&pageSize={page_size}");
23        if !type_filter.is_empty() {
24            path.push_str(&format!("&type={}", urlencoding(type_filter)));
25        }
26        self.billing_get(&path, signal).await
27    }
28
29    /// 获取未读通知数量。对应 TS `getUnreadCount`。
30    pub async fn get_unread_count(&self, signal: Option<CancellationToken>) -> Result<i64> {
31        let resp: NotificationUnreadCount = self
32            .billing_get("/notifications/unread-count", signal)
33            .await?;
34        Ok(resp.unread_count)
35    }
36
37    /// 标记单条通知已读。对应 TS `markNotificationRead`。
38    pub async fn mark_notification_read(
39        &self,
40        id: &str,
41        signal: Option<CancellationToken>,
42    ) -> Result<()> {
43        self.notify_void(
44            http::Method::PUT,
45            &format!("/notifications/{}/read", urlencoding(id)),
46            None,
47            signal,
48        )
49        .await
50    }
51
52    /// 标记全部通知已读。对应 TS `markAllNotificationsRead`。
53    pub async fn mark_all_notifications_read(
54        &self,
55        signal: Option<CancellationToken>,
56    ) -> Result<()> {
57        self.notify_void(http::Method::PUT, "/notifications/read-all", None, signal)
58            .await
59    }
60
61    /// 删除通知。对应 TS `deleteNotification`。
62    pub async fn delete_notification(
63        &self,
64        id: &str,
65        signal: Option<CancellationToken>,
66    ) -> Result<()> {
67        self.notify_void(
68            http::Method::DELETE,
69            &format!("/notifications/{}", urlencoding(id)),
70            None,
71            signal,
72        )
73        .await
74    }
75
76    /// 注册推送设备 token。对应 TS `registerDevice`。
77    ///
78    /// **@experimental** 网关尚未提供 `/devices/*` 与 `/notification-preferences/*` 端点,调用将 404。
79    /// 后端实现落地前请勿在生产使用。
80    pub async fn register_device(
81        &self,
82        reg: &DeviceRegistration,
83        signal: Option<CancellationToken>,
84    ) -> Result<()> {
85        let body = serde_json::to_string(reg)
86            .map_err(|e| Error::other(format!("serialize device registration: {e}")))?;
87        self.notify_void(http::Method::POST, "/devices/register", Some(&body), signal)
88            .await
89    }
90
91    /// 注销推送设备 token。对应 TS `unregisterDevice`。
92    ///
93    /// **@experimental** 见 [`Self::register_device`]。
94    pub async fn unregister_device(
95        &self,
96        token: &str,
97        signal: Option<CancellationToken>,
98    ) -> Result<()> {
99        self.notify_void(
100            http::Method::DELETE,
101            &format!("/devices/{}", urlencoding(token)),
102            None,
103            signal,
104        )
105        .await
106    }
107
108    /// 获取通知偏好设置。对应 TS `listNotificationPreferences`。
109    ///
110    /// **@experimental** 见 [`Self::register_device`]。
111    pub async fn list_notification_preferences(
112        &self,
113        signal: Option<CancellationToken>,
114    ) -> Result<Vec<NotificationPreference>> {
115        self.billing_get("/notification-preferences", signal).await
116    }
117
118    /// 更新通知偏好。对应 TS `updateNotificationPreference`。
119    ///
120    /// **@experimental** 见 [`Self::register_device`]。
121    pub async fn update_notification_preference(
122        &self,
123        type_code: &str,
124        pref: &NotificationPreference,
125        signal: Option<CancellationToken>,
126    ) -> Result<()> {
127        let body = serde_json::to_string(pref)
128            .map_err(|e| Error::other(format!("serialize preference: {e}")))?;
129        self.notify_void(
130            http::Method::PUT,
131            &format!("/notification-preferences/{}", urlencoding(type_code)),
132            Some(&body),
133            signal,
134        )
135        .await
136    }
137
138    /// 通知域内部:发起返回 `ApiResponse<unknown>` 的写端点(PUT/DELETE/POST),仅做业务码检查。
139    /// 对应 TS `doJSON<APIResponse<unknown>>(...)`(忽略 data)。
140    async fn notify_void(
141        &self,
142        method: http::Method,
143        path: &str,
144        body: Option<&str>,
145        signal: Option<CancellationToken>,
146    ) -> Result<()> {
147        let (bytes, _) = self
148            .do_json_full_raw(method, path, body, signal, DEFAULT_JSON_TIMEOUT_MS, None)
149            .await?;
150        // 空体成功 → 跳业务码检查(方案 §4.4)。
151        if bytes.is_empty() {
152            return Ok(());
153        }
154        let env: ApiResponse<serde_json::Value> = serde_json::from_slice(&bytes)
155            .map_err(|e| Error::other(format!("{path}: decode: {e}")))?;
156        if let Some(err) = env.business_error() {
157            return Err(err);
158        }
159        Ok(())
160    }
161}