posthog_rs/client/
async_client.rs

1use std::time::Duration;
2
3use reqwest::{header::CONTENT_TYPE, Client as HttpClient};
4
5use crate::{event::InnerEvent, Error, Event};
6
7use super::ClientOptions;
8
9/// A [`Client`] facilitates interactions with the PostHog API over HTTP.
10pub struct Client {
11    options: ClientOptions,
12    client: HttpClient,
13}
14
15/// This function constructs a new client using the options provided.
16pub async fn client<C: Into<ClientOptions>>(options: C) -> Client {
17    let options = options.into();
18    let client = HttpClient::builder()
19        .timeout(Duration::from_secs(options.request_timeout_seconds))
20        .build()
21        .unwrap(); // Unwrap here is as safe as `HttpClient::new`
22    Client { options, client }
23}
24
25impl Client {
26    /// Capture the provided event, sending it to PostHog.
27    pub async fn capture(&self, event: Event) -> Result<(), Error> {
28        let inner_event = InnerEvent::new(event, self.options.api_key.clone());
29
30        let payload =
31            serde_json::to_string(&inner_event).map_err(|e| Error::Serialization(e.to_string()))?;
32
33        self.client
34            .post(&self.options.api_endpoint)
35            .header(CONTENT_TYPE, "application/json")
36            .body(payload)
37            .send()
38            .await
39            .map_err(|e| Error::Connection(e.to_string()))?;
40
41        Ok(())
42    }
43
44    /// Capture a collection of events with a single request. This function may be
45    /// more performant than capturing a list of events individually.
46    pub async fn capture_batch(&self, events: Vec<Event>) -> Result<(), Error> {
47        let events: Vec<_> = events
48            .into_iter()
49            .map(|event| InnerEvent::new(event, self.options.api_key.clone()))
50            .collect();
51
52        let payload =
53            serde_json::to_string(&events).map_err(|e| Error::Serialization(e.to_string()))?;
54
55        self.client
56            .post(&self.options.api_endpoint)
57            .header(CONTENT_TYPE, "application/json")
58            .body(payload)
59            .send()
60            .await
61            .map_err(|e| Error::Connection(e.to_string()))?;
62
63        Ok(())
64    }
65}