Skip to main content

loops_so/client/
events.rs

1use http::StatusCode;
2use serde_json::{Map, Value};
3
4use super::{ContactId, EventOptions, LoopsClient, check, mailing_lists_value, merge_properties};
5use crate::error::Result;
6use crate::generated::{
7    EventSuccessResponse, SendEventRequest, SendEventRequestHeader, SendEventResponse,
8};
9use crate::routes::Route;
10
11impl LoopsClient {
12    /// Send an event to trigger workflows and emails for a contact.
13    ///
14    /// An idempotency key is generated when `options` does not carry one.
15    pub async fn send_event(
16        &self,
17        event_name: &str,
18        contact: ContactId,
19        options: EventOptions,
20    ) -> Result<EventSuccessResponse> {
21        const ACTION: &str = "send event";
22        self.validate_email(contact.email_address())?;
23        let header = SendEventRequestHeader {
24            idempotency_key: Some(
25                options
26                    .idempotency_key
27                    .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
28            ),
29        };
30        check(&header)?;
31        let headers = http::HeaderMap::try_from(&header).map_err(|err| {
32            crate::LoopsError::InvalidInput(format!("Invalid idempotency key: {err}"))
33        })?;
34
35        // The spec models this body as a oneOf over email/userId with contact
36        // properties as extra top-level keys, which the generator leaves as raw JSON.
37        let mut body = Map::new();
38        body.insert("eventName".to_owned(), Value::from(event_name));
39        if let Some(email) = contact.email_address() {
40            body.insert("email".to_owned(), Value::from(email));
41        }
42        if let Some(user_id) = contact.user_id_value() {
43            body.insert("userId".to_owned(), Value::from(user_id));
44        }
45        if !options.event_properties.is_empty() {
46            body.insert(
47                "eventProperties".to_owned(),
48                Value::Object(options.event_properties),
49            );
50        }
51        if let Some(lists) = mailing_lists_value(&options.mailing_lists) {
52            body.insert("mailingLists".to_owned(), lists);
53        }
54        merge_properties(
55            &mut body,
56            options.contact_properties,
57            &[
58                "eventName",
59                "email",
60                "userId",
61                "eventProperties",
62                "mailingLists",
63            ],
64            ACTION,
65        )?;
66
67        let raw = self
68            .send(Route::SendEvent, &[], |r| r.headers(headers).json(&body))
69            .await?;
70        if raw.status == StatusCode::CONFLICT {
71            return Err(raw.failure_with("Idempotency key conflict"));
72        }
73        match raw.parse(ACTION, SendEventRequest::parse_response).await? {
74            SendEventResponse::Ok(response) => Ok(response),
75            _ => Err(raw.unexpected(ACTION)),
76        }
77    }
78}