use serde::{Deserialize, Serialize};
use std::fmt;
macro_rules! define_id {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct $name(String);
impl $name {
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_inner(self) -> String {
self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl AsRef<str> for $name {
fn as_ref(&self) -> &str {
&self.0
}
}
impl From<String> for $name {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for $name {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
};
}
define_id!(
CustomerId
);
define_id!(
ProductId
);
define_id!(
PriceId
);
define_id!(
PricingModelId
);
define_id!(
SubscriptionId
);
define_id!(
SubscriptionItemId
);
define_id!(
SubscriptionItemFeatureId
);
define_id!(
InvoiceId
);
define_id!(
InvoiceLineItemId
);
define_id!(
PaymentId
);
define_id!(
PaymentMethodId
);
define_id!(
CheckoutSessionId
);
define_id!(
PurchaseId
);
define_id!(
FeatureId
);
define_id!(
ProductFeatureId
);
define_id!(
DiscountId
);
define_id!(
UsageMeterId
);
define_id!(
UsageEventId
);
define_id!(
WebhookId
);
define_id!(
ApiKeyId
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_customer_id_creation() {
let id = CustomerId::new("cus_123");
assert_eq!(id.as_str(), "cus_123");
assert_eq!(id.to_string(), "cus_123");
}
#[test]
fn test_customer_id_from_string() {
let id: CustomerId = "cus_456".into();
assert_eq!(id.as_str(), "cus_456");
}
#[test]
fn test_customer_id_equality() {
let id1 = CustomerId::new("cus_123");
let id2 = CustomerId::new("cus_123");
let id3 = CustomerId::new("cus_456");
assert_eq!(id1, id2);
assert_ne!(id1, id3);
}
#[test]
fn test_customer_id_serialization() {
let id = CustomerId::new("cus_test");
let json = serde_json::to_string(&id).unwrap();
assert_eq!(json, r#""cus_test""#);
let deserialized: CustomerId = serde_json::from_str(&json).unwrap();
assert_eq!(id, deserialized);
}
#[test]
fn test_different_id_types_are_distinct() {
let customer_id = CustomerId::new("id_123");
let product_id = ProductId::new("id_123");
assert_eq!(customer_id.as_str(), product_id.as_str());
}
}