use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::client::CdpClient;
use crate::error::Result;
use crate::session::{CdpSession, SessionEvent};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "Value")]
pub struct NoReturns {}
pub trait Command: Serialize {
const METHOD: &'static str;
type Returns: DeserializeOwned;
}
pub trait Event: DeserializeOwned {
const METHOD: &'static str;
}
impl From<Value> for NoReturns {
fn from(_: Value) -> Self {
Self {}
}
}
pub fn decode<E: Event>(method: &str, params: &Value) -> Option<Result<E>> {
if method != E::METHOD {
return None;
}
Some(E::deserialize(params).map_err(Into::into))
}
impl SessionEvent {
pub fn decode<E: Event>(&self) -> Option<Result<E>> {
decode(&self.method, &self.params)
}
}
impl CdpSession<'_> {
pub async fn send<C: Command>(&self, params: C) -> Result<C::Returns> {
self.call(C::METHOD, params).await
}
pub async fn wait_for<E: Event>(&self, timeout_ms: u64) -> Result<E> {
let params = self.wait_for_event(E::METHOD, timeout_ms).await?;
Ok(serde_json::from_value(params)?)
}
}
impl CdpClient {
pub async fn send<C: Command>(&self, params: C) -> Result<C::Returns> {
self.call(C::METHOD, params).await
}
pub async fn wait_for<E: Event>(&self, timeout_ms: u64) -> Result<E> {
let params = self.wait_for_event(E::METHOD, timeout_ms).await?;
Ok(serde_json::from_value(params)?)
}
}