#![deny(missing_docs)]
use nestrs_core::{Injectable, ProviderRegistry};
use std::sync::Arc;
pub const DEFAULT_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
pub const DEFAULT_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
pub struct HttpService {
client: reqwest::Client,
}
#[derive(Clone, Debug)]
pub struct HttpServiceOptions {
pub request_timeout: std::time::Duration,
pub connect_timeout: std::time::Duration,
}
impl Default for HttpServiceOptions {
fn default() -> Self {
Self {
request_timeout: DEFAULT_REQUEST_TIMEOUT,
connect_timeout: DEFAULT_CONNECT_TIMEOUT,
}
}
}
impl Injectable for HttpService {
fn construct(_registry: &ProviderRegistry) -> Arc<Self> {
Arc::new(Self::from_options(&HttpServiceOptions::default()))
}
}
impl HttpService {
pub fn from_options(options: &HttpServiceOptions) -> Self {
let client = reqwest::Client::builder()
.connect_timeout(options.connect_timeout)
.timeout(options.request_timeout)
.build()
.unwrap_or_else(|e| {
panic!("nestrs_http HttpService: reqwest::Client::build failed: {e}")
});
Self { client }
}
pub fn client(&self) -> &reqwest::Client {
&self.client
}
pub fn get(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
self.client.get(url)
}
pub fn post(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
self.client.post(url)
}
pub fn put(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
self.client.put(url)
}
pub fn patch(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
self.client.patch(url)
}
pub fn delete(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
self.client.delete(url)
}
}
pub struct HttpModule;
impl HttpModule {
pub fn register() -> Self {
Self
}
}
impl std::fmt::Debug for HttpModule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HttpModule").finish()
}
}
impl std::fmt::Debug for HttpService {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HttpService").finish_non_exhaustive()
}
}
#[cfg(feature = "reqwest")]
pub use reqwest;