diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 9fd45e0..bf0b6c8 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -20,3 +20,32 @@ jobs: run: cargo build --verbose - name: Run tests run: cargo test --verbose + + fmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install rustfmt + run: rustup toolchain install stable --profile minimal --component rustfmt && rustup default stable + - name: Check formatting + run: cargo fmt --all --check + + clippy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install clippy + run: rustup toolchain install stable --profile minimal --component clippy && rustup default stable + - name: Run clippy + run: cargo clippy --all-targets -- -D warnings + + docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install toolchain + run: rustup toolchain install stable --profile minimal && rustup default stable + - name: Build documentation + run: cargo doc --no-deps + env: + RUSTDOCFLAGS: -D warnings diff --git a/Cargo.toml b/Cargo.toml index 2c6dcde..78c5717 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,3 +21,13 @@ base64 = "0.13.0" http = "0.2.9" tokio = {version="1.28.1", features = ["rt", "macros"]} serde_json = "1.0" + +[lints.rust] +missing_docs = "warn" +rust_2018_idioms = { level = "warn", priority = -1 } +unreachable_pub = "warn" +unused_qualifications = "warn" + +[lints.clippy] +pedantic = { level = "warn", priority = -1 } +use_self = "warn" diff --git a/README.md b/README.md index 2a387df..2f510f3 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ use std::collections::HashMap; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize the client with your access token - let client = Client::new("".to_string())?; + let client = Client::new("")?; // Make a request with parameters let mut params = HashMap::new(); diff --git a/docs/crates-io.md b/docs/crates-io.md index 2a6eb40..80d8a33 100644 --- a/docs/crates-io.md +++ b/docs/crates-io.md @@ -74,7 +74,7 @@ use std::collections::HashMap; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize the client with your access token - let client = Client::new("".to_string())?; + let client = Client::new("")?; // Make a request with parameters let mut params = HashMap::new(); diff --git a/examples/api_calls.rs b/examples/api_calls.rs index 877e1d9..b100cd4 100644 --- a/examples/api_calls.rs +++ b/examples/api_calls.rs @@ -1,11 +1,23 @@ +//! Calls Openapi® APIs with a Bearer access token. + use openapi_sdk::Client; use serde::Serialize; use std::collections::HashMap; +#[derive(Serialize)] +struct Query { + country_code: String, +} + +#[derive(Serialize)] +struct Payload { + limit: u64, + query: Query, +} + #[tokio::main] async fn main() -> Result<(), Box> { - let token = "".to_string(); - let client = Client::new(token)?; + let client = Client::new("")?; let mut params = HashMap::new(); params.insert("denominazione", "altravia"); @@ -21,18 +33,7 @@ async fn main() -> Result<(), Box> { ) .await?; - println!("API Response: {}", result); - - #[derive(Serialize)] - struct Query { - country_code: String, - } - - #[derive(Serialize)] - struct Payload { - limit: u64, - query: Query, - } + println!("API Response: {result}"); let query = Query { country_code: "IT".to_string(), @@ -48,7 +49,7 @@ async fn main() -> Result<(), Box> { ) .await?; - println!("POST API Response: {}", result); + println!("POST API Response: {result}"); Ok(()) -} \ No newline at end of file +} diff --git a/examples/token_generation.rs b/examples/token_generation.rs index dc91022..a9ab401 100644 --- a/examples/token_generation.rs +++ b/examples/token_generation.rs @@ -1,3 +1,5 @@ +//! Creates an Openapi® OAuth access token for a list of scopes. + use openapi_sdk::OauthClient; use serde::{Deserialize, Serialize}; @@ -22,4 +24,4 @@ async fn main() -> Result<(), Box> { println!("Token created successfully!"); Ok(()) -} \ No newline at end of file +} diff --git a/src/lib.rs b/src/lib.rs index 25edb93..427eb13 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ -use base64; +//! Rust client for the Openapi® marketplace APIs. + use http::header::{AUTHORIZATION, CONTENT_TYPE}; use http::HeaderMap; use reqwest::Client as reqwest_client; @@ -13,7 +14,7 @@ const OAUTH_BASE_URL: &str = "https://oauth.openapi.it"; // Base URL for test OAuth endpoint const TEST_OAUTH_BASE_URL: &str = "https://test.oauth.openapi.it"; -/// OAuth client for OpenAPI authentication and token management +/// OAuth client for Openapi® authentication and token management pub struct OauthClient { client: reqwest_client, url: &'static str, @@ -26,7 +27,15 @@ impl OauthClient { /// * `username` - The API username /// * `apikey` - The API key for authentication /// * `test` - If true, uses test environment; otherwise production - pub fn new(username: &str, apikey: &str, test: bool) -> Result { + /// + /// # Errors + /// + /// Returns an error if the underlying HTTP client cannot be built. + #[expect( + clippy::missing_panics_doc, + reason = "base64 credentials always form a valid header value" + )] + pub fn new(username: &str, apikey: &str, test: bool) -> Result { // Select appropriate base URL based on environment let url = if test { TEST_OAUTH_BASE_URL @@ -47,15 +56,19 @@ impl OauthClient { let client = reqwest::Client::builder() .default_headers(headers) .build()?; - Ok(OauthClient { client, url }) + Ok(Self { client, url }) } /// Retrieves available OAuth scopes /// /// # Arguments /// * `limit` - If true, returns limited scope information + /// + /// # Errors + /// + /// Returns an error if the request fails or the response body cannot be read. pub async fn get_scopes(&self, limit: bool) -> Result { - let params = [("limit", limit as u8)]; + let params = [("limit", u8::from(limit))]; let url = format!("{}/scopes", self.url); let response: Response = self.client.get(url).query(¶ms).send().await?; // TODO: Add error handling for non-2xx status codes with descriptive messages @@ -68,6 +81,10 @@ impl OauthClient { /// # Arguments /// * `scopes` - List of permission scopes for the token /// * `ttl` - Token lifetime in seconds + /// + /// # Errors + /// + /// Returns an error if the request fails or the response body cannot be read. pub async fn create_token( &self, scopes: Vec<&'static str>, @@ -92,6 +109,10 @@ impl OauthClient { /// /// # Arguments /// * `scope` - The scope to filter tokens by + /// + /// # Errors + /// + /// Returns an error if the request fails or the response body cannot be read. pub async fn get_tokens(&self, scope: &'static str) -> Result { let params = [("scope", scope)]; let url = format!("{}/token", self.url); @@ -105,6 +126,10 @@ impl OauthClient { /// /// # Arguments /// * `id` - The unique identifier of the token to delete + /// + /// # Errors + /// + /// Returns an error if the request fails or the response body cannot be read. pub async fn delete_token(&self, id: String) -> Result { let url = format!("{}/token/{}", self.url, id); let response: Response = self.client.delete(url).send().await?; @@ -118,6 +143,10 @@ impl OauthClient { /// # Arguments /// * `period` - The time period (e.g., "day", "month") /// * `date` - The date in appropriate format + /// + /// # Errors + /// + /// Returns an error if the request fails or the response body cannot be read. pub async fn get_counters( &self, period: &'static str, @@ -141,7 +170,15 @@ impl Client { /// /// # Arguments /// * `token` - The Bearer token for API authentication - pub fn new(token: String) -> Result { + /// + /// # Errors + /// + /// Returns an error if the underlying HTTP client cannot be built. + /// + /// # Panics + /// + /// Panics if `token` contains characters that are not valid in an HTTP header value. + pub fn new(token: &str) -> Result { let auth_header = format!("Bearer {token}"); let mut headers = HeaderMap::new(); @@ -153,7 +190,7 @@ impl Client { let client = reqwest::Client::builder() .default_headers(headers) .build()?; - Ok(Client { client }) + Ok(Self { client }) } /// Makes an HTTP request to the specified URL @@ -166,6 +203,14 @@ impl Client { /// /// # Returns /// The response body as a JSON string + /// + /// # Errors + /// + /// Returns an error if the request fails or the response body cannot be read. + /// + /// # Panics + /// + /// Panics if `method` is not a valid HTTP method. pub async fn request( &self, method: &str, @@ -176,8 +221,6 @@ impl Client { where T: Serialize, { - let url = format!("{}", url); - // TODO: Replace unwrap() with proper error handling for invalid HTTP methods // Consider returning a descriptive error like "Invalid HTTP method: {method}" let mut request = self.client.request(Method::from_str(method).unwrap(), url); @@ -215,11 +258,11 @@ mod tests { /// Tests successful creation of API client with Bearer token #[test] fn test_api_client_creation() { - let client = Client::new("test_token".to_string()); + let client = Client::new("test_token"); assert!(client.is_ok()); } // TODO: Add test for invalid credentials and verify error messages are descriptive // TODO: Add test for invalid HTTP method in request() and verify error handling // TODO: Add integration tests for API endpoints with mock server -} \ No newline at end of file +}