1use crate::error::Error;
2
3const DEFAULT_API_BASE_URL: &str = "https://api.replicate.com/v1/";
4const API_KEY_ENV_VAR: &str = "REPLICATE_API_KEY";
5
6#[derive(Debug, Clone)]
7pub struct Config {
8 pub api_key: String,
9 pub base_url: String,
10}
11
12impl Config {
13 pub fn new(api_key: impl Into<String>) -> Self {
14 Self {
15 api_key: api_key.into(),
16 base_url: DEFAULT_API_BASE_URL.to_string(),
17 }
18 }
19
20 pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
21 self.base_url = base_url.into();
22 self
23 }
24
25 pub fn from_env() -> Result<Self, Error> {
26 let api_key =
27 std::env::var(API_KEY_ENV_VAR).map_err(|_| Error::MissingApiKey(API_KEY_ENV_VAR))?;
28 Ok(Self::new(api_key))
29 }
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35 use pretty_assertions::assert_eq;
36
37 #[test]
38 fn should_use_default_values() {
39 let api_key = "replicate-api-key";
40 let config = Config::new(api_key);
41
42 assert_eq!(config.api_key, api_key);
43 assert_eq!(config.base_url, DEFAULT_API_BASE_URL);
44 }
45
46 #[test]
47 fn should_set_custom_url() {
48 let api_key = "replicate-api-key";
49
50 let config = Config::new(api_key).with_base_url("https://custom-api.replicate.com");
51 assert_eq!(config.base_url, "https://custom-api.replicate.com");
52 }
53}