rust_woocommerce/controllers/
mod.rs1use serde::{Deserialize, Serialize};
2
3use anyhow::Result;
4
5use crate::Config;
6pub mod coupons;
7pub mod customers;
8pub mod data;
9pub mod entities;
10pub mod order_notes;
11pub mod orders;
12pub mod payment_gateways;
13pub mod product_attribute_terms;
14pub mod product_attributes;
15pub mod product_categories;
16pub mod product_reviews;
17pub mod product_shipping_classes;
18pub mod product_tags;
19pub mod product_variations;
20pub mod products;
21pub mod refunds;
22pub mod reports;
23pub mod settings;
24pub mod shipping_methods;
25pub mod shipping_zone_locations;
26pub mod shipping_zone_methods;
27pub mod shipping_zones;
28pub mod tax_classes;
29pub mod tax_rates;
30pub mod webhooks;
31
32pub trait Entity: Serialize + for<'de> Deserialize<'de> + Clone + Send + 'static {
33 fn endpoint() -> String;
34 fn child_endpoint(parent_id: i32) -> String;
35}
36#[derive(Clone)]
38pub struct ApiClient {
39 ck: String,
40 cs: String,
41 base_url: url::Url,
42 client: reqwest::Client,
43}
44
45impl ApiClient {
46 pub fn new(config: &Config) -> Result<Self> {
56 let ck = config.woo.ck.to_owned();
57 let cs = config.woo.cs.to_owned();
58 let client = reqwest::Client::builder().gzip(true).build()?;
59 let base_url = match url::Url::parse(&config.woo.host) {
60 Ok(url) => url.join("/wp-json/wc/v3/")?,
61 Err(_) => {
62 let raw_url = format!("https://{}", config.woo.host);
63 let url = url::Url::parse(&raw_url)?;
64 url.join("/wp-json/wc/v3/")?
65 }
66 };
67 Ok(Self {
68 ck,
69 cs,
70 base_url,
71 client,
72 })
73 }
74 pub fn init(host: impl AsRef<str>, ck: impl AsRef<str>, cs: impl AsRef<str>) -> Result<Self> {
76 let client = reqwest::Client::builder().gzip(true).build()?;
77 let base_url = match url::Url::parse(host.as_ref()) {
78 Ok(url) => url.join("/wp-json/wc/v3/")?,
79 Err(_) => {
80 let raw_url = format!("https://{url}", url = host.as_ref());
81 let url = url::Url::parse(&raw_url)?;
82 url.join("/wp-json/wc/v3/")?
83 }
84 };
85 Ok(Self {
86 client,
87 base_url,
88 ck: ck.as_ref().into(),
89 cs: cs.as_ref().into(),
90 })
91 }
92 pub fn from_env() -> Result<Self> {
98 let ck = std::env::var("WOO_CK")?;
99 let cs = std::env::var("WOO_CS")?;
100 let base_url_raw = std::env::var("BASE_URL")?;
101 let base_url = url::Url::parse(&format!("{base_url_raw}/wp-json/wc/v3/"))?;
102 let client = reqwest::Client::builder().gzip(true).build()?;
103
104 Ok(Self {
105 ck,
106 cs,
107 base_url,
108 client,
109 })
110 }
111 pub fn ck(&self) -> String {
113 self.ck.clone()
114 }
115 pub fn cs(&self) -> String {
117 self.cs.clone()
118 }
119 pub fn client(&self) -> reqwest::Client {
121 self.client.clone()
122 }
123 pub fn base_url(&self) -> String {
125 self.base_url.to_string()
126 }
127}