use super::{
ActionName, ActionRef, ActionSpec, AddonName, AddonSpec, Fields, HttpMethod, ModuleName,
ModuleSpec, ParamInput, RouteSpec, TableName, TableSpec, ViewSpec,
};
use crate::action::functional::FnAction;
use crate::action::DynAction;
use crate::action::{Action as BusinessAction, ActionContext, PermissionMode, TypedAction};
use crate::error::BaseError;
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::future::Future;
use std::marker::PhantomData;
use std::sync::Arc;
#[derive(Default)]
pub struct Actions(Vec<(ActionSpec, Arc<dyn DynAction>)>);
impl Actions {
pub const fn new() -> Self {
Self(Vec::new())
}
pub fn action<A>(mut self, spec: ActionSpec, handler: A) -> Self
where
A: DynAction,
{
self.0.push((spec, Arc::new(handler)));
self
}
pub fn native<A>(mut self, handler: A) -> Self
where
A: BusinessAction + TypedAction,
{
let name = handler.name();
let path = if handler.path().is_empty() {
format!("/{name}")
} else {
handler.path().to_string()
};
let permissions = handler
.permissions()
.iter()
.map(|permission| permission.name().to_string())
.collect::<Vec<_>>();
let mut spec = ActionSpec::new(
super::ActionName::__from_validated_literal(name),
super::RouteSpec::new(handler.http_method(), path, name),
)
.display_name(handler.display_name())
.description(handler.description())
.permissions(permissions, handler.permission_mode())
.public(handler.is_public())
.response_kind(handler.response_kind())
.success_status(handler.success_status())
.params(<A as BusinessAction>::params());
if let Some(multipart) = handler.multipart_spec() {
spec = spec.multipart(multipart);
}
for call in handler.calls() {
spec = spec.calls(call);
}
self.0.push((spec, Arc::new(handler)));
self
}
pub(crate) fn into_vec(self) -> Vec<(ActionSpec, Arc<dyn DynAction>)> {
self.0
}
}
impl std::fmt::Debug for Actions {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Actions")
.field("len", &self.0.len())
.finish()
}
}
impl ModuleSpec {
pub fn native_action<A>(self, handler: A) -> Self
where
A: BusinessAction + TypedAction,
{
let mut values = Actions::new().native(handler).into_vec();
let (mut spec, handler) = values.remove(0);
if spec.route.operation_id == spec.name.as_str() {
spec.route.operation_id = format!("{}.{}", self.name, spec.name);
}
self.dyn_action(spec, handler)
}
pub fn action_fn<F, I, O, Fut>(self, name: ActionName, handler: F) -> ActionFnBuilder<F, I, O>
where
F: Fn(ActionContext, I) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O, BaseError>> + Send,
I: ParamInput + DeserializeOwned + JsonSchema + Send + 'static,
O: Serialize + JsonSchema + Send + 'static,
{
let spec = ActionSpec::new(
name.clone(),
RouteSpec::new(HttpMethod::Post, format!("/{name}"), name.as_str()),
);
ActionFnBuilder {
module: self,
spec,
handler,
marker: PhantomData,
}
}
}
pub struct ActionFnBuilder<F, I, O> {
module: ModuleSpec,
spec: ActionSpec,
handler: F,
marker: PhantomData<fn(I) -> O>,
}
impl<F, I, O> ActionFnBuilder<F, I, O> {
#[must_use]
pub fn route(mut self, method: HttpMethod, path: impl Into<String>) -> Self {
self.spec.route.method = method;
self.spec.route.path = path.into();
self
}
#[must_use]
pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
self.spec.display_name = display_name.into();
self
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.spec.description = description.into();
self
}
#[must_use]
pub fn permissions<P, S>(mut self, permissions: P) -> Self
where
P: IntoIterator<Item = S>,
S: Into<String>,
{
self.spec.permissions = permissions.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
self.spec.permission_mode = mode;
self
}
#[must_use]
pub fn public(mut self) -> Self {
self.spec.is_public = true;
self
}
#[must_use]
pub fn success_status(mut self, status: u16) -> Self {
self.spec.success_status = status;
self
}
#[must_use]
pub fn response_kind(mut self, kind: super::ActionResponseKind) -> Self {
self.spec.response_kind = kind;
self
}
#[must_use]
pub fn multipart(mut self, multipart: super::MultipartSpec) -> Self {
self.spec = self.spec.multipart(multipart);
self
}
#[must_use]
pub fn calls(mut self, action: ActionRef) -> Self {
self.spec.calls.push(action);
self
}
pub fn register<Fut>(mut self) -> ModuleSpec
where
F: Fn(ActionContext, I) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O, BaseError>> + Send,
I: ParamInput + DeserializeOwned + JsonSchema + Send + 'static,
O: Serialize + JsonSchema + Send + 'static,
{
self.spec.params = I::params().into_vec();
match (
serde_json::to_value(schemars::schema_for!(I)),
serde_json::to_value(schemars::schema_for!(O)),
) {
(Ok(input_schema), Ok(output_schema)) => {
self.spec.input_schema = input_schema;
self.spec.output_schema = output_schema;
}
(Err(error), _) | (_, Err(error)) => {
self.spec.contract_error = Some(error.to_string());
}
}
let mut spec = self.spec;
if spec.route.operation_id == spec.name.as_str() {
spec.route.operation_id = format!("{}.{}", self.module.name, spec.name);
}
self.module
.dyn_action(spec, Arc::new(FnAction::<F, I, O>::new(self.handler)))
}
}
#[derive(Debug, Clone, Default)]
pub struct Modules(Vec<ModuleSpec>);
impl Modules {
pub const fn new() -> Self {
Self(Vec::new())
}
pub fn module<M>(mut self, module: M) -> Self
where
M: Module,
{
self.0.push(module.into_spec());
self
}
pub(crate) fn into_vec(self) -> Vec<ModuleSpec> {
self.0
}
}
pub trait Module: Sized {
fn name(&self) -> ModuleName;
fn table(&self) -> Option<TableName> {
None
}
fn fields(&self) -> Fields {
Fields::new()
}
fn configure_table(&self, table: TableSpec) -> TableSpec {
table
}
fn actions(&self) -> Actions {
Actions::new()
}
fn views(&self) -> Vec<ViewSpec> {
Vec::new()
}
fn into_spec(self) -> ModuleSpec {
let module_name = self.name();
let mut spec = ModuleSpec::new(module_name.clone());
if let Some(table) = self.table() {
let table = TableSpec::new(table).fields(self.fields());
spec = spec.table(self.configure_table(table));
}
for (mut action, handler) in self.actions().into_vec() {
if action.route.operation_id == action.name.as_str() {
action.route.operation_id = format!("{}.{}", module_name, action.name);
}
spec = spec.dyn_action(action, handler);
}
for view in self.views() {
spec = spec.view(view);
}
spec
}
}
pub trait Addon: Sized {
fn name(&self) -> AddonName;
fn modules(&self) -> Modules;
fn dependencies(&self) -> Vec<AddonName> {
Vec::new()
}
fn into_spec(self) -> AddonSpec {
let mut spec = AddonSpec::new(self.name());
for dependency in self.dependencies() {
spec = spec.depends_on(dependency);
}
for module in self.modules().into_vec() {
spec = spec.module(module);
}
spec
}
}
impl<T> From<T> for AddonSpec
where
T: Addon,
{
fn from(value: T) -> Self {
value.into_spec()
}
}