Skip to main content

supabase_rust/
client.rs

1use std::env;
2
3use reqwest::Client;
4
5use crate::Supabase;
6
7impl Supabase {
8    /// Creates a new Supabase client.
9    ///
10    /// If no parameters are provided, it will attempt to read from environment
11    /// variables: `SUPABASE_URL`, `SUPABASE_API_KEY`, and `SUPABASE_JWT_SECRET`.
12    pub fn new(url: Option<&str>, api_key: Option<&str>, jwt: Option<&str>) -> Self {
13        Self {
14            client: Client::new(),
15            url: url
16                .map(Into::into)
17                .unwrap_or_else(|| env::var("SUPABASE_URL").unwrap_or_default()),
18            api_key: api_key
19                .map(Into::into)
20                .unwrap_or_else(|| env::var("SUPABASE_API_KEY").unwrap_or_default()),
21            jwt: jwt
22                .map(Into::into)
23                .unwrap_or_else(|| env::var("SUPABASE_JWT_SECRET").unwrap_or_default()),
24            bearer_token: None,
25        }
26    }
27
28    /// Sets the bearer token for authenticated requests.
29    pub fn set_bearer_token(&mut self, token: impl Into<String>) {
30        self.bearer_token = Some(token.into());
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn test_client_creation() {
40        let client = Supabase::new(
41            Some("https://example.supabase.co"),
42            Some("test-key"),
43            Some("test-jwt"),
44        );
45        assert_eq!(client.url, "https://example.supabase.co");
46        assert_eq!(client.api_key, "test-key");
47        assert_eq!(client.jwt, "test-jwt");
48    }
49
50    #[test]
51    fn test_client_from_env() {
52        // When env vars are not set, fields should be empty
53        let client = Supabase::new(None, None, None);
54        assert!(client.bearer_token.is_none());
55    }
56
57    #[test]
58    fn test_set_bearer_token() {
59        let mut client = Supabase::new(None, None, None);
60        client.set_bearer_token("my-token");
61        assert_eq!(client.bearer_token, Some("my-token".to_string()));
62    }
63}