Skip to content

Commit

Permalink
Add method user_agent to wasm::ClientBuilder.
Browse files Browse the repository at this point in the history
  • Loading branch information
FirelightFlagboy committed Oct 31, 2023
1 parent cdffa57 commit c02a1d7
Showing 1 changed file with 70 additions and 2 deletions.
72 changes: 70 additions & 2 deletions src/wasm/client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use http::{HeaderMap, Method};
use http::header::USER_AGENT;
use http::{HeaderMap, HeaderValue, Method};
use js_sys::{Promise, JSON};
use std::convert::TryInto;
use std::{fmt, future::Future, sync::Arc};
use url::Url;
use wasm_bindgen::prelude::{wasm_bindgen, UnwrapThrowExt as _};
Expand Down Expand Up @@ -266,12 +268,33 @@ impl ClientBuilder {

/// Returns a 'Client' that uses this ClientBuilder configuration
pub fn build(mut self) -> Result<Client, crate::Error> {
if let Some(err) = self.config.error {
return Err(err);
}

let config = std::mem::take(&mut self.config);
Ok(Client {
config: Arc::new(config),
})
}

/// Sets the `User-Agent` header to be used by this client.
pub fn user_agent<V>(mut self, value: V) -> ClientBuilder
where
V: TryInto<HeaderValue>,
V::Error: Into<http::Error>,
{
match value.try_into() {
Ok(value) => {
self.config.headers.insert(USER_AGENT, value);
}
Err(e) => {
self.config.error = Some(crate::error::builder(e.into()));
}
}
self
}

/// Sets the default headers for every request
pub fn default_headers(mut self, headers: HeaderMap) -> ClientBuilder {
for (key, value) in headers.iter() {
Expand All @@ -287,15 +310,17 @@ impl Default for ClientBuilder {
}
}

#[derive(Clone, Debug)]
#[derive(Debug)]
struct Config {
headers: HeaderMap,
error: Option<crate::Error>,
}

impl Default for Config {
fn default() -> Config {
Config {
headers: HeaderMap::new(),
error: None,
}
}
}
Expand Down Expand Up @@ -376,4 +401,47 @@ mod tests {
"request headers don't change client defaults"
);
}

#[wasm_bindgen_test]
fn user_agent_header() {
use crate::header::USER_AGENT;

let client = crate::Client::builder()
.user_agent("FooBar/1.2.3")
.build()
.expect("client");

let mut req = client
.get("https://www.example.com")
.build()
.expect("request");

// Merge the client headers with the request's one.
client.merge_headers(&mut req);
let headers1 = req.headers();

// Confirm that we have the `User-Agent` header set
assert_eq!(
headers1.get(USER_AGENT).unwrap(),
"FooBar/1.2.3",
"The user-agent header was not set: {req:#?}"
);

// Now we try to overwrite the `User-Agent` value

let mut req2 = client
.get("https://www.example.com")
.header(USER_AGENT, "Another-User-Agent/42")
.build()
.expect("request 2");

client.merge_headers(&mut req2);
let headers2 = req2.headers();

assert_eq!(
headers2.get(USER_AGENT).expect("headers2 user agent"),
"Another-User-Agent/42",
"Was not able to overwrite the User-Agent value on the request-builder"
);
}
}

0 comments on commit c02a1d7

Please sign in to comment.