use sea_orm::{ColumnTrait, Condition, ConnectionTrait, DbErr, EntityTrait, QueryFilter};
use crate::{config::SlugOptions, error::SlugError, text::slugify};
pub async fn unique_slug<E, C>(
db: &C,
column: E::Column,
text: &str,
options: &SlugOptions,
) -> Result<String, SlugError>
where
E: EntityTrait,
C: ConnectionTrait,
{
let base = slugify(text, options);
pick_free::<E, C>(db, column, &base, options, Condition::all()).await
}
pub async fn find_by_slug<E, C>(
db: &C,
column: E::Column,
slug: &str,
) -> Result<Option<E::Model>, DbErr>
where
E: EntityTrait,
C: ConnectionTrait,
{
E::find().filter(column.eq(slug)).one(db).await
}
pub async fn pick_free<E, C>(
db: &C,
column: E::Column,
base: &str,
options: &SlugOptions,
scope: Condition,
) -> Result<String, SlugError>
where
E: EntityTrait,
C: ConnectionTrait,
{
if base.is_empty() {
return Err(SlugError::Empty);
}
if !options.always_suffix() && is_free::<E, C>(db, column, base, options, &scope).await? {
return Ok(base.to_string());
}
let mut attempt = options.first_suffix();
loop {
let candidate = options.with_suffix(base, attempt);
if is_free::<E, C>(db, column, &candidate, options, &scope).await? {
return Ok(candidate);
}
attempt += 1;
}
}
async fn is_free<E, C>(
db: &C,
column: E::Column,
slug: &str,
options: &SlugOptions,
scope: &Condition,
) -> Result<bool, DbErr>
where
E: EntityTrait,
C: ConnectionTrait,
{
if options.is_reserved(slug) {
return Ok(false);
}
Ok(!is_taken::<E, C>(db, column, slug, scope.clone()).await?)
}
async fn is_taken<E, C>(
db: &C,
column: E::Column,
slug: &str,
scope: Condition,
) -> Result<bool, DbErr>
where
E: EntityTrait,
C: ConnectionTrait,
{
let row = E::find()
.filter(column.eq(slug))
.filter(scope)
.one(db)
.await?;
Ok(row.is_some())
}