use std::collections::HashMap;
use std::sync::Arc;
use crate::api::{Plugin, PluginError, PluginHook};
pub struct PluginRegistry {
plugins: HashMap<String, Arc<dyn Plugin>>,
}
impl PluginRegistry {
#[must_use]
pub fn new() -> Self {
Self {
plugins: HashMap::new(),
}
}
pub fn register(&mut self, plugin: Arc<dyn Plugin>) {
self.plugins.insert(plugin.id().to_string(), plugin);
}
#[must_use]
pub fn get(&self, id: &str) -> Option<&Arc<dyn Plugin>> {
self.plugins.get(id)
}
#[must_use]
pub fn list(&self) -> Vec<&str> {
self.plugins.keys().map(String::as_str).collect()
}
pub async fn execute_hook(
&self,
hook: PluginHook,
data: serde_json::Value,
) -> Vec<Result<serde_json::Value, PluginError>> {
let mut results = Vec::new();
for plugin in self.plugins.values() {
if plugin.hooks().contains(&hook) {
results.push(plugin.execute_hook(hook, data.clone()).await);
}
}
results
}
}
impl Default for PluginRegistry {
fn default() -> Self {
Self::new()
}
}