use crate::context::Context;
use crate::error::JsonApiError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operation {
List,
Create,
Read,
Update,
Delete,
}
impl Operation {
pub fn as_str(self) -> &'static str {
match self {
Self::List => "list",
Self::Create => "create",
Self::Read => "read",
Self::Update => "update",
Self::Delete => "delete",
}
}
pub fn is_write(self) -> bool {
matches!(self, Self::Create | Self::Update | Self::Delete)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Event<'a> {
pub operation: Operation,
pub resource: &'a str,
pub id: Option<&'a str>,
}
#[derive(Debug, Clone, Copy)]
pub enum Outcome {
Succeeded {
status: u16,
},
Failed {
status: u16,
},
}
impl Outcome {
pub fn status(&self) -> u16 {
match self {
Self::Succeeded { status } | Self::Failed { status } => *status,
}
}
pub fn succeeded(&self) -> bool {
matches!(self, Self::Succeeded { .. })
}
}
pub trait Hook: Send + Sync + 'static {
fn before(&self, _event: &Event<'_>, _ctx: &Context) -> Result<(), JsonApiError> {
Ok(())
}
fn after(&self, _event: &Event<'_>, _outcome: &Outcome, _ctx: &Context) {}
}
#[derive(Default, Clone)]
pub struct Hooks(std::sync::Arc<Vec<Box<dyn Hook>>>);
impl Hooks {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, hook: impl Hook) -> Self {
let mut hooks = std::mem::take(&mut self.0);
let vec =
std::sync::Arc::get_mut(&mut hooks).expect("hooks are built before they are shared");
vec.push(Box::new(hook));
Self(hooks)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn before(&self, event: &Event<'_>, ctx: &Context) -> Result<(), JsonApiError> {
for hook in self.0.iter() {
hook.before(event, ctx)?;
}
Ok(())
}
pub fn after(&self, event: &Event<'_>, outcome: &Outcome, ctx: &Context) {
for hook in self.0.iter() {
hook.after(event, outcome, ctx);
}
}
}
impl std::fmt::Debug for Hooks {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Hooks")
.field("count", &self.0.len())
.finish()
}
}