use sea_orm::{
sea_query::ValueType, ActiveModelTrait, ActiveValue, ColumnTrait, Condition, ConnectionTrait,
EntityTrait, Iterable, PrimaryKeyToColumn, Value,
};
use crate::{config::SlugOptions, db::pick_free, error::SlugError, text::slugify};
type Column<A> = <<A as ActiveModelTrait>::Entity as EntityTrait>::Column;
type Predicate<A> = Box<dyn Fn(&A) -> bool + Send + Sync>;
type ScopeFn<A> = Box<dyn Fn(&A) -> Condition + Send + Sync>;
pub trait Sluggable: ActiveModelTrait + Send {
fn slug_config() -> SlugConfig<Self>;
}
pub struct SlugConfig<A: ActiveModelTrait> {
sources: Vec<Column<A>>,
target: Column<A>,
options: SlugOptions,
on_create: bool,
on_update: bool,
prevent_overwrite: bool,
skip_when: Option<Predicate<A>>,
scope: Option<ScopeFn<A>>,
}
impl<A: ActiveModelTrait> SlugConfig<A> {
pub fn new(sources: impl IntoIterator<Item = Column<A>>, target: Column<A>) -> Self {
Self {
sources: sources.into_iter().collect(),
target,
options: SlugOptions::default(),
on_create: true,
on_update: false,
prevent_overwrite: false,
skip_when: None,
scope: None,
}
}
#[must_use]
pub fn options(mut self, options: SlugOptions) -> Self {
self.options = options;
self
}
#[must_use]
pub const fn on_create(mut self, enabled: bool) -> Self {
self.on_create = enabled;
self
}
#[must_use]
pub const fn on_update(mut self, enabled: bool) -> Self {
self.on_update = enabled;
self
}
#[must_use]
pub const fn prevent_overwrite(mut self, enabled: bool) -> Self {
self.prevent_overwrite = enabled;
self
}
#[must_use]
pub fn skip_when(mut self, skip: impl Fn(&A) -> bool + Send + Sync + 'static) -> Self {
self.skip_when = Some(Box::new(skip));
self
}
#[must_use]
pub fn scope(mut self, scope: impl Fn(&A) -> Condition + Send + Sync + 'static) -> Self {
self.scope = Some(Box::new(scope));
self
}
}
pub async fn fill_slug<A, C>(model: A, db: &C, insert: bool) -> Result<A, SlugError>
where
A: Sluggable,
C: ConnectionTrait,
{
let config = A::slug_config();
fill_slug_with(model, db, insert, &config).await
}
pub async fn fill_slug_with<A, C>(
mut model: A,
db: &C,
insert: bool,
config: &SlugConfig<A>,
) -> Result<A, SlugError>
where
A: ActiveModelTrait + Send,
C: ConnectionTrait,
{
if !should_generate(&model, insert, config) {
return Ok(model);
}
let base = slugify(&source_text(&model, &config.sources), &config.options);
let mut scope = config
.scope
.as_ref()
.map_or_else(Condition::all, |scope| scope(&model));
if !insert {
if let Some(itself) = primary_key_condition(&model) {
scope = scope.add(itself.not());
}
}
let slug = pick_free::<A::Entity, C>(db, config.target, &base, &config.options, scope).await?;
model.set(config.target, slug.into());
Ok(model)
}
fn should_generate<A: ActiveModelTrait>(model: &A, insert: bool, config: &SlugConfig<A>) -> bool {
let enabled = if insert {
config.on_create
} else {
config.on_update
&& config
.sources
.iter()
.any(|column| model.get(*column).is_set())
};
if !enabled {
return false;
}
if config.skip_when.as_ref().is_some_and(|skip| skip(model)) {
return false;
}
!(config.prevent_overwrite && text_of(model.get(config.target)).is_some_and(|s| !s.is_empty()))
}
fn source_text<A: ActiveModelTrait>(model: &A, sources: &[Column<A>]) -> String {
sources
.iter()
.filter_map(|column| text_of(model.get(*column)))
.collect::<Vec<_>>()
.join(" ")
}
fn text_of(value: ActiveValue<Value>) -> Option<String> {
let value = value.into_value()?;
<Option<String> as ValueType>::try_from(value)
.ok()
.flatten()
}
fn primary_key_condition<A: ActiveModelTrait>(model: &A) -> Option<Condition> {
let mut condition = Condition::all();
for key in <<A::Entity as EntityTrait>::PrimaryKey as Iterable>::iter() {
let column = key.into_column();
let value = model.get(column).into_value()?;
condition = condition.add(column.eq(value));
}
Some(condition)
}