use std::future::Future;
use crate::error::NetworkError;
use crate::network::{
Route, UrlMatcher, UrlPattern, WaitForRequestBuilder, WaitForResponseBuilder, WebSocket,
};
use super::Page;
impl Page {
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.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.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, crate::network::HarReplayOptions::default())
.await
}
pub async fn route_from_har_with_options(
&self,
path: impl AsRef<std::path::Path>,
options: crate::network::HarReplayOptions,
) -> Result<(), NetworkError> {
if self.closed {
return Err(NetworkError::Aborted);
}
let handler = std::sync::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
}
pub fn wait_for_request<M: UrlMatcher + Clone + 'static>(
&self,
pattern: M,
) -> WaitForRequestBuilder<'_, M> {
WaitForRequestBuilder::new(&self.connection, &self.session_id, pattern)
}
pub fn wait_for_response<M: UrlMatcher + Clone + 'static>(
&self,
pattern: M,
) -> WaitForResponseBuilder<'_, M> {
WaitForResponseBuilder::new(&self.connection, &self.session_id, pattern)
}
pub async fn on_websocket<F, Fut>(&self, handler: F)
where
F: Fn(WebSocket) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
self.websocket_manager.set_handler(handler).await;
}
pub async fn off_websocket(&self) {
self.websocket_manager.remove_handler().await;
}
}