wakapi 0.5.1

Wakatime API client
Documentation
/// Credentials sent with each request.
enum Auth {
    /// Value of the HTTP Basic credentials.
    Basic(String),
    /// OAuth 2.0 access token.
    Bearer(String),
}

pub struct WakapiClient {
    api_url: String,
    auth: Auth,
}

impl WakapiClient {
    /// Create a client authenticating with HTTP Basic Auth.
    ///
    /// Wakatime API keys are write-only, so this can't be used with wakatime.com's read endpoints
    /// (use [`WakapiClient::with_token`] instead). It remains useful for Wakatime-compatible
    /// servers that still accept API keys on these endpoints.
    pub fn new(api_url: &str, api_key: &str) -> Self {
        Self {
            api_url: api_url.to_string(),
            auth: Auth::Basic(api_key.to_string()),
        }
    }

    /// Create a client authenticating with an OAuth 2.0 access token.
    ///
    /// For your own account, get a token from <https://wakatime.com/oauth>.
    pub fn with_token(api_url: &str, token: &str) -> Self {
        Self {
            api_url: api_url.to_string(),
            auth: Auth::Bearer(token.to_string()),
        }
    }

    /// Build the full URL for the given endpoint, replacing /:user/ with "/current/" (for now).
    pub fn build_url(&self, endpoint: &str, url_params: Option<String>) -> String {
        let mut url = self.api_url.clone() + endpoint;
        url = url.replace("/:user/", "/current/");
        if let Some(params) = url_params {
            url = url + "?" + &params;
        }
        url
    }

    /// Get Authorization header value for the client.
    pub fn get_auth_header(&self) -> String {
        match &self.auth {
            Auth::Basic(api_key) => format!("Basic {}", api_key),
            Auth::Bearer(token) => format!("Bearer {}", token),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_uses_basic_auth() {
        let client = WakapiClient::new("https://wakatime.com", "MTIzNDU=");
        assert_eq!(client.get_auth_header(), "Basic MTIzNDU=");
    }

    #[test]
    fn with_token_uses_bearer_auth() {
        let client = WakapiClient::with_token("https://wakatime.com", "waka_tok_12345");
        assert_eq!(client.get_auth_header(), "Bearer waka_tok_12345");
    }
}