use std::future::Future;
use std::sync::Arc;
use crate::error::NetworkError;
use crate::network::{HarReplayOptions, Route, UrlPattern};
use super::BrowserContext;
impl BrowserContext {
pub async fn route<M, H, Fut>(&self, pattern: M, handler: H) -> Result<(), NetworkError>
where
M: Into<UrlPattern>,
H: Fn(Route) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), NetworkError>> + Send + 'static,
{
if self.is_closed() {
return Err(NetworkError::Aborted);
}
self.route_registry.route(pattern, handler).await
}
pub async fn route_predicate<P, H, Fut>(
&self,
predicate: P,
handler: H,
) -> Result<(), NetworkError>
where
P: Fn(&str) -> bool + Send + Sync + 'static,
H: Fn(Route) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), NetworkError>> + Send + 'static,
{
if self.is_closed() {
return Err(NetworkError::Aborted);
}
self.route_registry
.route_predicate(predicate, handler)
.await
}
pub async fn unroute(&self, pattern: &str) {
self.route_registry.unroute(pattern).await;
}
pub async fn unroute_all(&self) {
self.route_registry.unroute_all().await;
}
pub async fn route_from_har(
&self,
path: impl AsRef<std::path::Path>,
) -> Result<(), NetworkError> {
self.route_from_har_with_options(path, HarReplayOptions::default())
.await
}
pub async fn route_from_har_with_options(
&self,
path: impl AsRef<std::path::Path>,
options: HarReplayOptions,
) -> Result<(), NetworkError> {
if self.is_closed() {
return Err(NetworkError::Aborted);
}
let handler = Arc::new(
crate::network::HarReplayHandler::from_file(path)
.await?
.with_options(options),
);
let route_handler = crate::network::har_replay::create_har_route_handler(handler);
self.route_registry.route("**/*", route_handler).await
}
}