You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
880 B
32 lines
880 B
use sea_orm::{error::DbErr, ColumnTrait, ConnectionTrait, EntityTrait, QueryFilter};
|
|
use slug::slugify;
|
|
|
|
/// This generic function returns a slug that is not already used in the database to insert safely
|
|
pub async fn ensure_unique_slug<E, C, DB>(s: &String, column: C, db: &DB) -> Result<String, DbErr>
|
|
where
|
|
E: EntityTrait,
|
|
C: ColumnTrait,
|
|
DB: ConnectionTrait,
|
|
{
|
|
let mut slug = slugify(s);
|
|
let mut count = 0;
|
|
// This is inefficient, we could search for all slugs that start with the new slug and take the
|
|
// last one + 1
|
|
while E::find()
|
|
.filter(column.eq(slug.clone()))
|
|
.one(db)
|
|
.await?
|
|
.is_some()
|
|
{
|
|
count += 1;
|
|
if count == 1 {
|
|
slug += "-1";
|
|
} else {
|
|
slug.drain(0..slug.len() - 1);
|
|
slug = format!("{}{}", slug, count);
|
|
}
|
|
}
|
|
|
|
Ok(slug)
|
|
}
|