supabase_storage/
lib.rs

1use reqwest::{
2    header::{HeaderMap, HeaderValue},
3    Client,
4};
5use url::Url;
6
7pub mod build;
8pub mod config;
9pub mod model;
10
11use build::builder::Builder;
12use config::SupabaseConfig;
13
14/// A struct representing a Storage with an associated client and headers.
15pub struct Storage {
16    url: url::Url,
17    headers: HeaderMap,
18    client: Client,
19}
20
21impl Storage {
22    /// Creates a new `Storage` instance with the provided URL.
23    ///
24    /// # Arguments
25    ///
26    /// * `url` - The base URL for the storage.
27    ///
28    /// # Example
29    ///
30    /// ```
31    /// use supabase_storage::Storage;
32    ///
33    /// let _ = Storage::new("https://your_project_path/storage/v1");
34    /// ```
35    pub fn new<T>(url: T) -> Self
36    where
37        T: Into<String>,
38    {
39        Self {
40            url: Url::parse(&url.into()).unwrap(),
41            headers: HeaderMap::new(),
42            client: Client::new(),
43        }
44    }
45
46    /// Creates a new `Storage` instance with provided configuration.
47    ///
48    /// # Arguments
49    ///
50    /// * `config` - The `SupabaseConfig` containing the necessary configuration for Supabase.
51    ///
52    /// # Example
53    /// ```
54    /// use supabase_storage::{Storage, config::SupabaseConfig};
55    /// use dotenv::dotenv;
56    ///
57    /// dotenv().ok();
58    /// let config = SupabaseConfig::default();  // load values from .env file using the 'envy' crate
59    /// let storage = Storage::new_with_config(config);
60    /// ```
61    pub fn new_with_config(config: SupabaseConfig) -> Self {
62        let mut headers = HeaderMap::new();
63        if let Some(api_key) = config.supabase_api_key {
64            headers.insert(
65                "Authorization",
66                HeaderValue::from_str(&format!("Bearer {}", api_key))
67                    .expect("header value is invalid"),
68            );
69            headers.insert(
70                "apiKey",
71                HeaderValue::from_str(&format!("{}", api_key)).expect("header value is invalid"),
72            );
73        }
74
75        Self {
76            url: Url::parse(&config.supabase_url_storage).unwrap(),
77            headers,
78            client: Client::new(),
79        }
80    }
81
82    /// Creates a new `Builder` instance to build an action
83    ///
84    /// # Example
85    /// ```
86    /// use supabase_storage::Storage;
87    ///
88    /// let storage = Storage::new("https://your_project_path/storage/v1");
89    /// let builder = storage.from();
90    /// ```
91    pub fn from(&self) -> Builder {
92        Builder::new(self.url.clone(), self.headers.clone(), self.client.clone())
93    }
94}