parse_rs/analytics.rs
1// src/analytics.rs
2use crate::client::Parse;
3use crate::error::ParseError;
4use reqwest::Method;
5use serde_json::Value;
6
7impl Parse {
8 /// Tracks a custom event with optional dimensions.
9 ///
10 /// # Arguments
11 /// * `event_name`: The name of the event to track (e.g., "ButtonClicked", "ItemPurchased").
12 /// * `dimensions`: Optional key-value pairs to associate with the event.
13 ///
14 /// # Returns
15 /// A `Result` indicating success or a `ParseError`.
16 ///
17 /// This operation typically requires the Master Key, JavaScript Key, or REST API Key.
18 pub async fn track_event(
19 &self,
20 event_name: &str,
21 dimensions: Option<Value>,
22 ) -> Result<(), ParseError> {
23 if event_name.is_empty() {
24 return Err(ParseError::InvalidInput(
25 "Event name cannot be empty.".to_string(),
26 ));
27 }
28
29 let endpoint = format!("events/{}", event_name);
30
31 // The server expects an empty JSON object {} if dimensions are None.
32 let body = dimensions.unwrap_or_else(|| serde_json::json!({}));
33
34 let use_master_key = self.master_key.is_some();
35 // Analytics events are often not tied to a specific user session.
36 // The _request method will use JS or REST key if master_key is None and session_token is None.
37 let session_token_to_use = None;
38
39 // For analytics events, Parse Server responds with an empty JSON object {} and HTTP 200 OK on success.
40 // We don't need to deserialize a specific response body, just ensure the request was successful.
41 let _response_value: Value = self
42 ._request(
43 Method::POST,
44 &endpoint,
45 Some(&body),
46 use_master_key,
47 session_token_to_use,
48 )
49 .await?;
50
51 // If _request didn't return an error (e.g., non-2xx status), we consider it a success.
52 // The _request method itself handles non-successful HTTP status codes by returning ParseError.
53 Ok(())
54 }
55}