shopify_client/webhooks/
mod.rs

1pub mod types;
2
3use types::{
4    CustomersDataRequestPayload, CustomersRedactPayload, ShopRedactPayload, WebhookParseError,
5    WebhookPayload,
6};
7
8pub enum WebhookTopic {
9    CustomersDataRequest,
10    CustomersRedact,
11    ShopRedact,
12}
13
14impl WebhookTopic {
15    pub fn from_header(header: &str) -> Option<Self> {
16        match header.to_lowercase().as_str() {
17            "customers/data_request" => Some(WebhookTopic::CustomersDataRequest),
18            "customers/redact" => Some(WebhookTopic::CustomersRedact),
19            "shop/redact" => Some(WebhookTopic::ShopRedact),
20            _ => None,
21        }
22    }
23}
24
25pub fn parse_webhook(
26    topic: WebhookTopic,
27    payload: &str,
28) -> Result<WebhookPayload, WebhookParseError> {
29    match topic {
30        WebhookTopic::CustomersDataRequest => {
31            serde_json::from_str::<CustomersDataRequestPayload>(payload)
32                .map(WebhookPayload::CustomersDataRequest)
33                .map_err(|e| WebhookParseError::ParseError(e.to_string()))
34        }
35        WebhookTopic::CustomersRedact => serde_json::from_str::<CustomersRedactPayload>(payload)
36            .map(WebhookPayload::CustomersRedact)
37            .map_err(|e| WebhookParseError::ParseError(e.to_string())),
38        WebhookTopic::ShopRedact => serde_json::from_str::<ShopRedactPayload>(payload)
39            .map(WebhookPayload::ShopRedact)
40            .map_err(|e| WebhookParseError::ParseError(e.to_string())),
41    }
42}
43
44pub fn parse_webhook_with_header(
45    topic_header: &str,
46    payload: &str,
47) -> Result<WebhookPayload, WebhookParseError> {
48    let topic =
49        WebhookTopic::from_header(topic_header).ok_or(WebhookParseError::UnknownWebhookType)?;
50    parse_webhook(topic, payload)
51}
52
53pub fn try_parse_webhook(payload: &str) -> Result<WebhookPayload, WebhookParseError> {
54    if let Ok(data_request) = serde_json::from_str::<CustomersDataRequestPayload>(payload) {
55        return Ok(WebhookPayload::CustomersDataRequest(data_request));
56    }
57
58    if let Ok(customers_redact) = serde_json::from_str::<CustomersRedactPayload>(payload) {
59        return Ok(WebhookPayload::CustomersRedact(customers_redact));
60    }
61
62    if let Ok(shop_redact) = serde_json::from_str::<ShopRedactPayload>(payload) {
63        return Ok(WebhookPayload::ShopRedact(shop_redact));
64    }
65
66    Err(WebhookParseError::UnknownWebhookType)
67}