use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UploadthingConfig {
pub host: String,
pub user_agent: Option<String>,
pub api_key: Option<ApiKey>,
pub version: Option<String>,
}
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Serialize, Deserialize)]
#[derive(Clone)]
pub struct ApiKey {
pub prefix: Option<String>,
pub key: String,
}
impl ApiKey {
pub fn from_env() -> Option<ApiKey> {
match std::env::var("UPLOADTHING_SECRET") {
Ok(key) => Some(ApiKey { prefix: None, key }),
Err(_) => None,
}
}
}
impl Default for ApiKey {
fn default() -> ApiKey {
Self::from_env().expect("UPLOADTHING_SECRET environment variable is not set")
}
}
impl FromStr for ApiKey {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.splitn(2, ':').collect();
let (prefix, key) = match parts.as_slice() {
[prefix, key] => (Some(prefix.to_string()), key.to_string()),
[key] => (None, key.to_string()),
_ => return Err(()),
};
Ok(ApiKey { prefix, key })
}
}
impl std::fmt::Display for ApiKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.key)
}
}
impl UploadthingConfig {
pub fn new() -> UploadthingConfig {
UploadthingConfig::default()
}
pub fn builder() -> UploadthingConfigBuilder {
UploadthingConfigBuilder::new()
}
}
impl Default for UploadthingConfig {
fn default() -> UploadthingConfig {
UploadthingConfig {
host: "https://uploadthing.com".to_string(),
user_agent: Some(format!("utapi-rs/{}/rust", VERSION)),
api_key: ApiKey::from_env(),
version: Some(VERSION.to_string()),
}
}
}
pub struct UploadthingConfigBuilder {
config: UploadthingConfig,
}
impl UploadthingConfigBuilder {
pub fn new() -> Self {
UploadthingConfigBuilder {
config: UploadthingConfig::default(),
}
}
pub fn host(mut self, host: &str) -> Self {
self.config.host = host.to_string();
self
}
pub fn user_agent(mut self, user_agent: &str) -> Self {
self.config.user_agent = Some(user_agent.to_string());
self
}
pub fn api_key(mut self, api_key: &str) -> Self {
self.config.api_key = Some(ApiKey::from_str(api_key).unwrap_or_default());
self
}
pub fn version(mut self, version: &str) -> Self {
self.config.version = Some(version.to_string());
self
}
pub fn build(self) -> UploadthingConfig {
self.config
}
}
impl Default for UploadthingConfigBuilder {
fn default() -> Self {
Self::new()
}
}