bachs-sdk 0.1.0

Unofficial Rust SDK for the Bachs API — payments and billing for internet businesses.
Documentation
use crate::client::{Bachs, RequestOptions};
use crate::common::{ListParams, ListResponse, Metadata, Timestamp};
use crate::error::BachsResult;
use reqwest::Method;
use serde::{Deserialize, Serialize};

/// How a product is priced. Mirrors the `price_type` values referenced in
/// the Bachs docs (`fixed`, `free`, `pay_what_you_want`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PriceType {
    Fixed,
    Free,
    PayWhatYouWant,
    /// Any price type introduced by the API that this SDK version doesn't
    /// know about yet.
    #[serde(other)]
    Unknown,
}

/// The recurrence of a product's billing, for subscription products.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BillingInterval {
    Day,
    Week,
    Month,
    Year,
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecurringConfig {
    pub interval: BillingInterval,
    #[serde(default = "one")]
    pub interval_count: u32,
}

fn one() -> u32 {
    1
}

/// A product's price. Amounts are always decimal strings at the currency's
/// precision (e.g. `"29.00"`), never minor units.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Price {
    pub price_type: PriceType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<String>,
    /// Present for subscription products; absent for one-time products.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recurring: Option<RecurringConfig>,
}

impl Price {
    pub fn fixed(currency: impl Into<String>, amount: impl Into<String>) -> Self {
        Self {
            price_type: PriceType::Fixed,
            currency: Some(currency.into()),
            amount: Some(amount.into()),
            recurring: None,
        }
    }

    pub fn recurring(
        currency: impl Into<String>,
        amount: impl Into<String>,
        interval: BillingInterval,
    ) -> Self {
        Self {
            price_type: PriceType::Fixed,
            currency: Some(currency.into()),
            amount: Some(amount.into()),
            recurring: Some(RecurringConfig {
                interval,
                interval_count: 1,
            }),
        }
    }

    pub fn free() -> Self {
        Self {
            price_type: PriceType::Free,
            currency: None,
            amount: None,
            recurring: None,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateProductRequest {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub price: Price,
    /// `upload_id` from the Media resource, if the product has an image.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_upload_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
}

impl CreateProductRequest {
    pub fn new(name: impl Into<String>, price: Price) -> Self {
        Self {
            name: name.into(),
            description: None,
            price,
            image_upload_id: None,
            metadata: None,
        }
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateProductRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<Price>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
}

impl UpdateProductRequest {
    pub fn new() -> Self {
        Self::default()
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Product {
    /// Prefixed with `prod_`.
    pub product_id: String,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    pub price: Price,
    #[serde(default)]
    pub metadata: Metadata,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

pub struct Products<'a> {
    pub(crate) client: &'a Bachs,
}

impl<'a> Products<'a> {
    pub async fn create(&self, req: &CreateProductRequest) -> BachsResult<Product> {
        self.create_with_options(req, None).await
    }

    pub async fn create_with_options(
        &self,
        req: &CreateProductRequest,
        options: Option<&RequestOptions>,
    ) -> BachsResult<Product> {
        self.client
            .send(Method::POST, "/v1/products", Some(req), None, options)
            .await
    }

    pub async fn get(&self, product_id: &str) -> BachsResult<Product> {
        self.client
            .send::<(), _>(
                Method::GET,
                &format!("/v1/products/{product_id}"),
                None,
                None,
                None,
            )
            .await
    }

    pub async fn update(
        &self,
        product_id: &str,
        req: &UpdateProductRequest,
    ) -> BachsResult<Product> {
        self.client
            .send(
                Method::PATCH,
                &format!("/v1/products/{product_id}"),
                Some(req),
                None,
                None,
            )
            .await
    }

    pub async fn delete(&self, product_id: &str) -> BachsResult<()> {
        self.client
            .send::<(), serde_json::Value>(
                Method::DELETE,
                &format!("/v1/products/{product_id}"),
                None,
                None,
                None,
            )
            .await
            .map(|_| ())
    }

    pub async fn list(&self, params: &ListParams) -> BachsResult<ListResponse<Product>> {
        let query = params.to_query();
        self.client
            .send::<(), _>(Method::GET, "/v1/products", None, Some(&query), None)
            .await
    }
}