bachs-sdk 0.1.0

Unofficial Rust SDK for the Bachs API — payments and billing for internet businesses.
Documentation
use serde::Deserialize;
use std::fmt;

/// A single field-level validation error, as returned in the `errors` array
/// of a `400 VALIDATION_ERROR` response.
#[derive(Debug, Clone, Deserialize)]
pub struct FieldError {
    pub field: String,
    pub message: String,
    #[serde(rename = "type")]
    pub error_type: String,
}

/// The flat error body every Bachs API error response shares:
/// `{ "detail", "error_code", "doc_url"?, "errors"? }`.
#[derive(Debug, Clone, Deserialize)]
pub struct ApiErrorBody {
    pub detail: String,
    pub error_code: String,
    #[serde(default)]
    pub doc_url: Option<String>,
    #[serde(default)]
    pub errors: Vec<FieldError>,
}

impl fmt::Display for ApiErrorBody {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({})", self.detail, self.error_code)?;
        for e in &self.errors {
            write!(f, "\n  - {}: {}", e.field, e.message)?;
        }
        Ok(())
    }
}

/// Top-level error type returned by every fallible call in this SDK.
#[derive(Debug, thiserror::Error)]
pub enum BachsError {
    /// The API returned a non-2xx response with a parsed `ApiErrorBody`.
    #[error("Bachs API error [{status}]: {body}")]
    Api {
        status: u16,
        body: ApiErrorBody,
        /// Value of the `X-RateLimit-Reset` header, when present (Unix timestamp).
        rate_limit_reset: Option<i64>,
    },

    /// The API returned a non-2xx response whose body could not be parsed
    /// as the standard error shape.
    #[error("Bachs API error [{status}]: {raw_body}")]
    ApiUnparsed { status: u16, raw_body: String },

    /// Networking / transport failure (DNS, TLS, timeout, connection reset, ...).
    #[error("request failed: {0}")]
    Request(#[from] reqwest::Error),

    /// Failed to (de)serialize a request or response body.
    #[error("(de)serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// Failed to build a valid request URL.
    #[error("invalid URL: {0}")]
    Url(#[from] url::ParseError),

    /// Webhook signature verification failed.
    #[error("webhook signature verification failed: {0}")]
    WebhookSignature(String),

    /// A programmer error building the request (e.g. an invalid header value).
    #[error("invalid request: {0}")]
    InvalidRequest(String),
}

pub type BachsResult<T> = Result<T, BachsError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn api_error_body_display() {
        let body = ApiErrorBody {
            detail: "Invalid request".into(),
            error_code: "VALIDATION_ERROR".into(),
            doc_url: None,
            errors: vec![FieldError {
                field: "email".into(),
                message: "must be a valid email".into(),
                error_type: "value_error".into(),
            }],
        };
        let s = format!("{}", body);
        assert!(s.contains("Invalid request"));
        assert!(s.contains("VALIDATION_ERROR"));
        assert!(s.contains("email: must be a valid email"));
    }

    #[test]
    fn api_error_body_display_no_field_errors() {
        let body = ApiErrorBody {
            detail: "Not found".into(),
            error_code: "NOT_FOUND".into(),
            doc_url: Some("https://docs.bachs.io/errors/not_found".into()),
            errors: vec![],
        };
        let s = format!("{}", body);
        assert!(s.contains("Not found"));
        assert!(s.contains("NOT_FOUND"));
        assert!(!s.contains("-"));
    }

    #[test]
    fn bachs_error_api_display() {
        let err = BachsError::Api {
            status: 400,
            body: ApiErrorBody {
                detail: "Bad request".into(),
                error_code: "BAD_REQUEST".into(),
                doc_url: None,
                errors: vec![],
            },
            rate_limit_reset: None,
        };
        let s = format!("{err}");
        assert!(s.contains("[400]"));
        assert!(s.contains("Bad request"));
    }

    #[test]
    fn bachs_error_api_unparsed_display() {
        let err = BachsError::ApiUnparsed {
            status: 500,
            raw_body: "internal server error".into(),
        };
        let s = format!("{err}");
        assert!(s.contains("[500]"));
        assert!(s.contains("internal server error"));
    }

    #[test]
    fn bachs_error_webhook_signature_display() {
        let err = BachsError::WebhookSignature("bad sig".into());
        let s = format!("{err}");
        assert!(s.contains("bad sig"));
    }

    #[test]
    fn bachs_error_invalid_request_display() {
        let err = BachsError::InvalidRequest("bad header".into());
        let s = format!("{err}");
        assert!(s.contains("bad header"));
    }

    #[test]
    fn api_error_body_deserialization_with_all_fields() {
        let json = r#"{
            "detail": "something went wrong",
            "error_code": "INTERNAL_ERROR",
            "doc_url": "https://docs.bachs.io/errors/internal",
            "errors": [
                {"field": "amount", "message": "must be positive", "type": "value_error"}
            ]
        }"#;
        let body: ApiErrorBody = serde_json::from_str(json).unwrap();
        assert_eq!(body.detail, "something went wrong");
        assert_eq!(body.error_code, "INTERNAL_ERROR");
        assert_eq!(body.doc_url.as_deref(), Some("https://docs.bachs.io/errors/internal"));
        assert_eq!(body.errors.len(), 1);
        assert_eq!(body.errors[0].field, "amount");
    }
}