|
| 1 | +use std::{future::Future, pin::Pin}; |
| 2 | + |
| 3 | +use crate::utils::TursoConfig; |
| 4 | + |
| 5 | +pub trait DbAuthStrategy { |
| 6 | + fn resolve<'a>( |
| 7 | + &'a self, |
| 8 | + db_name: &'a str, |
| 9 | + client: &'a reqwest::Client, |
| 10 | + ) -> Pin<Box<dyn Future<Output = Result<TursoConfig, Box<dyn std::error::Error>>> + Send + 'a>>; |
| 11 | +} |
| 12 | + |
| 13 | +pub struct GlobeStrategy; |
| 14 | + |
| 15 | +impl DbAuthStrategy for GlobeStrategy { |
| 16 | + fn resolve<'a>( |
| 17 | + &'a self, |
| 18 | + db_name: &'a str, |
| 19 | + client: &'a reqwest::Client, |
| 20 | + ) -> Pin<Box<dyn Future<Output = Result<TursoConfig, Box<dyn std::error::Error>>> + Send + 'a>> |
| 21 | + { |
| 22 | + Box::pin(async move { |
| 23 | + let globe_auth_api = std::env::var("GLOBE_DS_API")?; |
| 24 | + |
| 25 | + let request_body = serde_json::json!({ "db_name": db_name }); |
| 26 | + |
| 27 | + let response = client |
| 28 | + .post(format!("{}/db/auth", globe_auth_api)) |
| 29 | + .body(request_body.to_string()) |
| 30 | + .send() |
| 31 | + .await |
| 32 | + .map_err(|_| "Failed to fetch auth credentials for database")?; |
| 33 | + |
| 34 | + if !response.status().is_success() { |
| 35 | + return Err(format!("Failed to get Auth Token: {}", response.status()).into()); |
| 36 | + } |
| 37 | + |
| 38 | + let json = response.json().await?; |
| 39 | + let config = serde_json::from_value(json)?; |
| 40 | + Ok(config) |
| 41 | + }) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +pub struct EnvVarStrategy; |
| 46 | + |
| 47 | +impl DbAuthStrategy for EnvVarStrategy { |
| 48 | + fn resolve<'a>( |
| 49 | + &'a self, |
| 50 | + _: &'a str, |
| 51 | + _client: &'a reqwest::Client, |
| 52 | + ) -> Pin<Box<dyn Future<Output = Result<TursoConfig, Box<dyn std::error::Error>>> + Send + 'a>> |
| 53 | + { |
| 54 | + Box::pin(async move { |
| 55 | + let url = std::env::var("TURSO_DB_URL")?; |
| 56 | + let token = std::env::var("TURSO_DB_TOKEN")?; |
| 57 | + |
| 58 | + Ok(TursoConfig { |
| 59 | + db_url: url, |
| 60 | + db_token: token, |
| 61 | + }) |
| 62 | + }) |
| 63 | + } |
| 64 | +} |
0 commit comments