Skip to main content

core_api/
webhook.rs

1//! Transport-neutral webhook body contract shared by desktop and embedded hosts.
2use crate::{ErrorResponse, ExceptionCode};
3use serde_json::Value;
4
5pub const GENERAL_WEBHOOK_PREFIX: &str = "/W";
6pub const GENERAL_WEBHOOK_ROUTE: &str = "/W/{code}";
7pub const MAX_WEBHOOK_BODY_BYTES: usize = 1024 * 1024;
8
9pub fn decode_body(content_type: &str, body: &[u8]) -> Result<Value, ErrorResponse> {
10    let media_type = content_type
11        .split(';')
12        .next()
13        .unwrap_or("")
14        .trim()
15        .to_ascii_lowercase();
16    let is_json = media_type == "application/json"
17        || (media_type.starts_with("application/") && media_type.ends_with("+json"));
18    if is_json {
19        serde_json::from_slice(body).map_err(|error| {
20            ErrorResponse::new(
21                ExceptionCode::BadRequest,
22                format!("Invalid webhook JSON: {error}"),
23            )
24        })
25    } else {
26        std::str::from_utf8(body)
27            .map(|text| Value::String(text.to_owned()))
28            .map_err(|_| {
29                ErrorResponse::new(ExceptionCode::BadRequest, "Webhook body must be UTF-8 text")
30            })
31    }
32}