Skip to content

Commit

Permalink
BaseHTTPClient: better constructor API, Default (#1517)
Browse files Browse the repository at this point in the history
to enable
- connecting to alternative servers, either production or test mocks
- unauthenticated calls, either for the initial auth or test mocks

This is needed for both #1438 and #1495

In the end, the API changes only by adding a `Default` trait
implementation which does no authentication.
Connecting to a mock server is achieved by assigning to the public
`base_url` field.
  • Loading branch information
mvidner committed Aug 1, 2024
2 parents ecc7147 + 7c155d2 commit 83ee1d3
Showing 1 changed file with 28 additions and 9 deletions.
37 changes: 28 additions & 9 deletions rust/agama-lib/src/base_http_client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use reqwest::{header, Client, Response};
use reqwest::{header, Response};
use serde::{de::DeserializeOwned, Serialize};

use crate::{auth::AuthToken, error::ServiceError};
Expand All @@ -21,15 +21,36 @@ use crate::{auth::AuthToken, error::ServiceError};
/// }
/// ```
pub struct BaseHTTPClient {
client: Client,
client: reqwest::Client,
pub base_url: String,
}

const API_URL: &str = "http://localhost/api";

impl Default for BaseHTTPClient {
/// A `default` client
/// - is NOT authenticated (maybe you want to call `new` instead)
/// - uses `localhost`
fn default() -> Self {
Self {
client: reqwest::Client::new(),
base_url: API_URL.to_owned(),
}
}
}

impl BaseHTTPClient {
// if there is need for client without authorization, create new constructor for it
/// Uses `localhost`, authenticates with [`AuthToken`].
pub fn new() -> Result<Self, ServiceError> {
Ok(Self {
client: Self::authenticated_client()?,
..Default::default()
})
}

fn authenticated_client() -> Result<reqwest::Client, ServiceError> {
// TODO: this error is subtly misleading, leading me to believe the SERVER said it,
// but in fact it is the CLIENT not finding an auth token
let token = AuthToken::find().ok_or(ServiceError::NotAuthenticated)?;

let mut headers = header::HeaderMap::new();
Expand All @@ -39,12 +60,10 @@ impl BaseHTTPClient {

headers.insert(header::AUTHORIZATION, value);

let client = Client::builder().default_headers(headers).build()?;

Ok(Self {
client,
base_url: API_URL.to_string(), // TODO: add support for remote server
})
let client = reqwest::Client::builder()
.default_headers(headers)
.build()?;
Ok(client)
}

/// Simple wrapper around [`Response`] to get object from response.
Expand Down

0 comments on commit 83ee1d3

Please sign in to comment.