Skip to content

Commit

Permalink
Merge pull request #20 from firstwaters/reqwest-maybe-middleware
Browse files Browse the repository at this point in the history
Add support for reqwest_maybe_middleware, make small structs Copy
  • Loading branch information
leontoeides authored Nov 15, 2023
2 parents eff6626 + 0c511d8 commit 1166d19
Show file tree
Hide file tree
Showing 285 changed files with 1,890 additions and 2,409 deletions.
6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "google_maps"
version = "3.3.2"
version = "3.4.0"
authors = [ "Dylan Bowker <[email protected]>" ]
edition = "2021"
categories = [ "api-bindings" ]
Expand Down Expand Up @@ -28,6 +28,7 @@ default = [
"enable-reqwest",
"reqwest/default-tls",
"reqwest/gzip",
"enable-reqwest-middleware",
"rust_decimal/serde",
]
# Google Maps Client API features:
Expand All @@ -42,6 +43,7 @@ roads = []
time_zone = [ "chrono", "chrono-tz" ]
# Reqwest features:
enable-reqwest = [ "reqwest", "backoff", "futures", "stream_throttle" ]
enable-reqwest-middleware = ["reqwest-maybe-middleware/middleware", "reqwest-middleware"]
brotli = [ "reqwest/brotli" ]
gzip = [ "reqwest/gzip" ]
native-tls = [ "reqwest/default-tls" ]
Expand All @@ -65,6 +67,8 @@ miette = "5"
percent-encoding = "2.3"
phf = { version = "0.11", features = [ "macros" ] }
reqwest = { version = "0.11", optional = true, default-features = false }
reqwest-middleware = {version = "0.2.3", optional = true}
reqwest-maybe-middleware = "0.2.2"
rust_decimal = { version = "1", features = [ "serde" ] }
rust_decimal_macros = "1"
serde = { version = "1.0", features = [ "derive" ] }
Expand Down
4 changes: 1 addition & 3 deletions src/client/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::client::GoogleMapsClient;
// =============================================================================

impl GoogleMapsClient {

// -------------------------------------------------------------------------
//
/// Completes the builder pattern into a final structure.
Expand Down Expand Up @@ -63,5 +62,4 @@ impl GoogleMapsClient {
pub fn finalize(&self) -> GoogleMapsClient {
self.build()
} // fn

} // impl
} // impl
29 changes: 17 additions & 12 deletions src/client/impls.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
use crate::client::GoogleMapsClient;
#[cfg(feature = "enable-reqwest")]
use crate::request_rate::RequestRate;
#[cfg(feature = "directions")]
use crate::directions::request::location::Location;
#[cfg(feature = "distance_matrix")]
use crate::directions::request::waypoint::Waypoint;
#[cfg(feature = "enable-reqwest")]
use crate::request_rate::RequestRate;
#[cfg(any(feature = "geocoding", feature = "time_zone", feature = "roads"))]
use crate::types::LatLng;
use crate::ReqError;
#[cfg(feature = "time_zone")]
use chrono::{DateTime, Utc};
use reqwest::Response;

// =============================================================================

impl GoogleMapsClient {

// -------------------------------------------------------------------------
//
/// Initialize the settings needed for a Google Cloud Maps API transaction.
Expand All @@ -24,18 +25,19 @@ impl GoogleMapsClient {
#[cfg(feature = "enable-reqwest")]
pub fn new(key: &str) -> GoogleMapsClient {

let reqwest_client = reqwest::Client::builder()
.user_agent(format!("RustGoogleMaps/{version}", version=env!("CARGO_PKG_VERSION")))
.user_agent(format!(
"RustGoogleMaps/{version}",
version = env!("CARGO_PKG_VERSION")
))
.build()
.unwrap();

GoogleMapsClient {
key: key.to_string(),
rate_limit: RequestRate::default(),
reqwest_client,
reqwest_client: reqwest_maybe_middleware::Client::Vanilla(reqwest_client),
} // GoogleMapsClient

} // fn

// -------------------------------------------------------------------------
Expand Down Expand Up @@ -183,10 +185,7 @@ impl GoogleMapsClient {
/// ```
#[cfg(feature = "geocoding")]
pub fn reverse_geocoding(
&self,
latlng: LatLng,
) -> crate::geocoding::reverse::ReverseRequest {
pub fn reverse_geocoding(&self, latlng: LatLng) -> crate::geocoding::reverse::ReverseRequest {
crate::geocoding::reverse::ReverseRequest::new(self, latlng)
} // fn

Expand Down Expand Up @@ -561,4 +560,10 @@ impl GoogleMapsClient {
crate::roads::snap_to_roads::request::Request::new(self, points)
} // fn

} // impl
pub async fn get_request(&self, url: &str) -> Result<Response, ReqError> {
match self.reqwest_client.get(url).build() {
Ok(request) => self.reqwest_client.execute(request).await,
Err(error) => Err(ReqError::from(error)),
}
}
} // impl
6 changes: 2 additions & 4 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ use crate::request_rate::RequestRate;
#[derive(Clone, Debug)]
pub struct GoogleMapsClient {

/// Your application's API key. This key identifies your application for
/// purposes of quota management. Learn how to [get a
/// key](https://developers.google.com/maps/documentation/geocoding/get-api-key).
Expand All @@ -52,6 +51,5 @@ pub struct GoogleMapsClient {
/// Allows you to optionally provide your own pre-configured reqwest client
/// that will be used by the Google Maps client.
#[cfg(feature = "enable-reqwest")]
pub reqwest_client: reqwest::Client,

} // struct
pub reqwest_client: reqwest_maybe_middleware::Client,
} // struct
4 changes: 1 addition & 3 deletions src/client/with_rate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use std::time::Duration;
// =============================================================================

impl GoogleMapsClient {

// -------------------------------------------------------------------------
//
/// Sets the rate limit for the specified API.
Expand Down Expand Up @@ -120,5 +119,4 @@ impl GoogleMapsClient {
self.rate_limit.with_rate(api, requests, per_duration);
self
} // fn

} // impl
} // impl
20 changes: 17 additions & 3 deletions src/client/with_reqwest_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::client::GoogleMapsClient;
// =============================================================================

impl GoogleMapsClient {

// -------------------------------------------------------------------------
//
/// Passes a user configured reqwest client for the Google Maps client to
Expand Down Expand Up @@ -34,8 +33,23 @@ impl GoogleMapsClient {
&mut self,
reqwest_client: reqwest::Client,
) -> &mut GoogleMapsClient {
self.reqwest_client = reqwest_client;
self.reqwest_client = reqwest_maybe_middleware::Client::Vanilla(reqwest_client);
self
} // fn

pub fn with_reqwest_middleware_client(
&mut self,
reqwest_client: reqwest_middleware::ClientWithMiddleware,
) -> &mut GoogleMapsClient {
self.reqwest_client = reqwest_maybe_middleware::Client::Middleware(reqwest_client);
self
} // fn

} // impl
pub fn with_reqwest(
&mut self,
reqwest_client: reqwest_maybe_middleware::Client,
) -> &mut GoogleMapsClient {
self.reqwest_client = reqwest_client;
self
} // fn
} // impl
16 changes: 14 additions & 2 deletions src/directions/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// -----------------------------------------------------------------------------

use crate::directions::response::status::Status;
use crate::ReqError;
use miette::Diagnostic;
use thiserror::Error;

Expand Down Expand Up @@ -95,7 +96,7 @@ pub enum Error {
RequestNotValidated,
/// The dependency library Reqwest generated an error.
#[cfg(feature = "enable-reqwest")]
Reqwest(reqwest::Error),
Reqwest(ReqError),
/// The dependency library Reqwest generated an error. The error could
/// not be passed normally so a `String` representation is passed instead.
#[cfg(feature = "enable-reqwest")]
Expand Down Expand Up @@ -296,6 +297,17 @@ impl From<reqwest::Error> for Error {
/// (`google_maps::directions::error::Error`) by wrapping it inside. This
/// function is required to use the `?` operator.
fn from(error: reqwest::Error) -> Error {
Error::Reqwest(ReqError::from(error))
} // fn
} // impl

#[cfg(feature = "enable-reqwest")]
impl From<ReqError> for Error {
/// This trait converts from an Reqwest error type (`reqwest::Error`) into a
/// Google Maps Directions API error type
/// (`google_maps::directions::error::Error`) by wrapping it inside. This
/// function is required to use the `?` operator.
fn from(error: ReqError) -> Error {
Error::Reqwest(error)
} // fn
} // impl
Expand All @@ -310,4 +322,4 @@ impl From<serde_json::error::Error> for Error {
fn from(error: serde_json::error::Error) -> Error {
Error::SerdeJson(error)
} // fn
} // impl
} // impl
38 changes: 11 additions & 27 deletions src/directions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,36 +96,20 @@ const OUTPUT_FORMAT: &str = "json"; // json or xml

pub use crate::directions::{
request::{
avoid::Avoid,
departure_time::DepartureTime,
location::Location,
Request as DirectionsRequest,
traffic_model::TrafficModel,
transit_mode::TransitMode,
transit_route_preference::TransitRoutePreference,
unit_system::UnitSystem,
waypoint::Waypoint,
avoid::Avoid, departure_time::DepartureTime, location::Location,
traffic_model::TrafficModel, transit_mode::TransitMode,
transit_route_preference::TransitRoutePreference, unit_system::UnitSystem,
waypoint::Waypoint, Request as DirectionsRequest,
}, // crate::directions::request
response::{
directions_distance::DirectionsDistance,
directions_duration::DirectionsDuration,
driving_maneuver::DrivingManeuver,
leg::Leg,
overview_polyline::OverviewPolyline,
polyline::Polyline,
directions_distance::DirectionsDistance, directions_duration::DirectionsDuration,
driving_maneuver::DrivingManeuver, leg::Leg, overview_polyline::OverviewPolyline,
polyline::Polyline, route::Route, status::Status as DirectionsStatus, step::Step,
transit_agency::TransitAgency, transit_currency::TransitCurrency,
transit_details::TransitDetails, transit_fare::TransitFare, transit_line::TransitLine,
transit_stop::TransitStop, transit_time::TransitTime, transit_vehicle::TransitVehicle,
Response as DirectionsResponse,
route::Route,
status::Status as DirectionsStatus,
step::Step,
transit_agency::TransitAgency,
transit_currency::TransitCurrency,
transit_details::TransitDetails,
transit_fare::TransitFare,
transit_line::TransitLine,
transit_stop::TransitStop,
transit_time::TransitTime,
transit_vehicle::TransitVehicle,
}, // crate::directions::response
travel_mode::TravelMode,
vehicle_type::VehicleType,
}; // use
}; // use
11 changes: 7 additions & 4 deletions src/directions/request/avoid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ pub enum Avoid {
/// by default.
Indoor = 2,
/// Indicates that the calculated route should avoid toll roads/bridges.
#[default] Tolls = 3,
#[default]
Tolls = 3,
} // enum

// -----------------------------------------------------------------------------
Expand All @@ -52,7 +53,7 @@ impl<'de> Deserialize<'de> for Avoid {
let string = String::deserialize(deserializer)?;
match Avoid::try_from(string.as_str()) {
Ok(variant) => Ok(variant),
Err(error) => Err(serde::de::Error::custom(error.to_string()))
Err(error) => Err(serde::de::Error::custom(error.to_string())),
} // match
} // fn
} // impl
Expand All @@ -62,7 +63,9 @@ impl<'de> Deserialize<'de> for Avoid {
impl Serialize for Avoid {
/// Manual implementation of `Serialize` for `serde`.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
where
S: Serializer,
{
serializer.serialize_str(std::convert::Into::<&str>::into(self))
} // fn
} // impl
Expand Down Expand Up @@ -161,4 +164,4 @@ impl Avoid {
Avoid::Tolls => "Tolls",
} // match
} // fn
} // impl
} // impl
19 changes: 10 additions & 9 deletions src/directions/request/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
// =============================================================================

impl<'a> Request<'a> {

// -------------------------------------------------------------------------
//
/// Builds the query string for the Google Maps Directions API based on the
Expand All @@ -15,9 +14,10 @@ impl<'a> Request<'a> {
/// This method accepts no arguments.
pub fn build(&'a mut self) -> Result<&'a mut Request, Error> {

// Ensure request has been validated before building the query string:
if !self.validated { return Err(Error::RequestNotValidated) }
if !self.validated {
return Err(Error::RequestNotValidated);
}

// Builds the "required parameters" portion of the query string:
let mut query = format!(
Expand Down Expand Up @@ -52,7 +52,8 @@ impl<'a> Request<'a> {
.collect::<Vec<String>>()
.join("|"),
NON_ALPHANUMERIC,
).to_string(),
)
.to_string(),
) // push_str
} // if

Expand Down Expand Up @@ -97,7 +98,8 @@ impl<'a> Request<'a> {
.collect::<Vec<String>>()
.join("|"),
NON_ALPHANUMERIC,
).to_string(),
)
.to_string(),
) // push_str
} // if

Expand Down Expand Up @@ -127,7 +129,8 @@ impl<'a> Request<'a> {
.collect::<Vec<String>>()
.join("|"),
NON_ALPHANUMERIC,
).to_string(),
)
.to_string(),
) // push_str
} // if

Expand All @@ -136,7 +139,5 @@ impl<'a> Request<'a> {

// Return modified Request struct to caller.
Ok(self)

} // fn

} // impl
} // impl
Loading

0 comments on commit 1166d19

Please sign in to comment.