use crate::core::macros::tmf_struct;
use crate::core::{EventKind, TmfType};
use super::client::TmfClient;
use super::error::Result;
use super::query::Query;
const HUB: &str = "hub";
tmf_struct! {
@name = "Hub";
pub struct Hub {
id: String,
href: String,
callback: String,
query: String,
}
}
tmf_struct! {
@name = "Hub";
pub struct HubCreate {
@required {
callback: String,
}
query: String,
}
}
impl HubCreate {
pub fn to(callback: impl Into<String>) -> Self {
Self::builder().callback(callback).build()
}
pub fn for_resource<T: TmfType>(callback: impl Into<String>, kind: EventKind) -> Self {
Self::for_event(callback, &kind.name_for::<T>())
}
pub fn for_event(callback: impl Into<String>, event_type: &str) -> Self {
Self::builder()
.callback(callback)
.query(format!("eventType={event_type}"))
.build()
}
}
#[allow(
async_fn_in_trait,
reason = "clients are used directly, not as trait objects"
)]
pub trait HubOps {
fn hub_client(&self) -> &TmfClient;
async fn register_listener(&self, hub: &HubCreate) -> Result<Hub> {
self.hub_client().create(HUB, hub).await
}
async fn unregister_listener(&self, id: &str) -> Result<()> {
self.hub_client().delete(HUB, id).await
}
async fn get_listener(&self, id: &str) -> Result<Hub> {
self.hub_client().get(HUB, id, &Query::new()).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hub_round_trips_unknown_members() {
let json = r#"{"callback":"https://me/cb","@type":"Hub","x-secret":"s"}"#;
let hub: Hub = serde_json::from_str(json).unwrap();
assert_eq!(hub.callback.as_deref(), Some("https://me/cb"));
assert_eq!(
serde_json::to_value(&hub).unwrap(),
serde_json::from_str::<serde_json::Value>(json).unwrap()
);
}
}