use futures::future::BoxFuture;
use futures::FutureExt;
use phlow_sdk::prelude::Value;
use phlow_sdk::structs::{ApplicationData, ModuleResponse};
use phlow_sdk::tracing::Dispatch;
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
#[derive(Debug, Clone, Default)]
pub struct PhlowModuleSchema {
pub input: Value,
pub output: Value,
pub input_order: Vec<String>,
}
impl PhlowModuleSchema {
pub fn new() -> Self {
Self::default()
}
pub fn with_input(mut self, input: Value) -> Self {
self.input = input;
self
}
pub fn with_output(mut self, output: Value) -> Self {
self.output = output;
self
}
pub fn with_input_order<I, S>(mut self, input_order: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.input_order = input_order.into_iter().map(Into::into).collect();
self
}
}
#[derive(Clone)]
pub struct PhlowModuleRequest {
pub input: Option<Value>,
pub payload: Option<Value>,
pub with: Value,
pub app_data: ApplicationData,
pub dispatch: Dispatch,
}
pub type PhlowModuleHandler =
Arc<dyn Fn(PhlowModuleRequest) -> BoxFuture<'static, ModuleResponse> + Send + Sync>;
#[derive(Clone, Default)]
pub struct PhlowModule {
schema: PhlowModuleSchema,
handler: Option<PhlowModuleHandler>,
}
impl PhlowModule {
pub fn new() -> Self {
Self::default()
}
pub fn set_schema(&mut self, schema: PhlowModuleSchema) -> &mut Self {
self.schema = schema;
self
}
pub fn set_handler<F, Fut>(&mut self, handler: F) -> &mut Self
where
F: Fn(PhlowModuleRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ModuleResponse> + Send + 'static,
{
self.handler = Some(Arc::new(move |request| handler(request).boxed()));
self
}
pub fn schema(&self) -> &PhlowModuleSchema {
&self.schema
}
pub(crate) fn handler(&self) -> Option<PhlowModuleHandler> {
self.handler.clone()
}
}
pub type InlineModules = HashMap<String, PhlowModule>;