sea-orm-sluggable 0.1.1

Unique, transliterated slugs for SeaORM entities
Documentation

sea-orm-sluggable

Unique, readable URL slugs for SeaORM entities, generated on save.

crates.io docs.rs CI license

Describe the slug once, and every insert gets one: "Rust for PHP developers" becomes rust-for-php-developers, the next one rust-for-php-developers-1. Think spatie/laravel-sluggable, for SeaORM.

Features

  • Automatic — one trait and one line in the save hook, no manual slug code
  • Unique — title, title-1, title-2, …, optionally only within a scope (per category, per tenant)
  • Any language — every script is transliterated to ASCII; official national rules per feature (uk today), or your own
  • Safe for URLs — slugs stay stable on update by default; reserved words (new, edit) never become slugs
  • Flexible — several source columns, separator, length, custom suffixes, conditional skipping
  • Tested — against a real database (in-memory SQLite), every API doc example compiled

Installation

[dependencies]
sea-orm-sluggable = "0.1"

Quick start

Describe the slug:

use sea_orm_sluggable::{SlugConfig, Sluggable};

impl Sluggable for posts::ActiveModel {
    fn slug_config() -> SlugConfig<Self> {
        SlugConfig::new([posts::Column::Title], posts::Column::Slug)
    }
}

Fill it in the save hook:

#[async_trait::async_trait]
impl ActiveModelBehavior for posts::ActiveModel {
    async fn before_save<C: ConnectionTrait>(self, db: &C, insert: bool) -> Result<Self, DbErr> {
        Ok(sea_orm_sluggable::fill_slug(self, db, insert).await?)
    }
}

That's it:

let post = posts::ActiveModel {
    title: Set("Hello, World!".to_string()),
    ..Default::default()
}
.insert(&db)
.await?;

assert_eq!(post.slug, "hello-world");

let found = sea_orm_sluggable::find_by_slug::<posts::Entity, _>(&db, posts::Column::Slug, "hello-world").await?;

When the slug is generated

SlugConfig::new([posts::Column::Title], posts::Column::Slug)
    .on_create(true)          // default: on
    .on_update(true)          // default: off, see below
    .prevent_overwrite(true)  // default: off; keep a slug an editor typed in
    .skip_when(|post: &posts::ActiveModel| post.draft.try_as_ref() == Some(&true))

on_update is off by default: changing a slug breaks every link to the old URL. When it is on, the slug is rebuilt when a source column is set on the model and gives another slug: saving the same title again keeps hello-1 as it is. A partial update that sets only some of several source columns leaves the slug alone, and a row never collides with its own slug.

Several source columns

SlugConfig::new([people::Column::FirstName, people::Column::LastName], people::Column::Slug)
// "Ada", "Lovelace" -> "ada-lovelace"; empty and NULL columns are skipped

Unique within a scope

SlugConfig::new([posts::Column::Title], posts::Column::Slug)
    .scope(|post: &posts::ActiveModel| {
        match post.category_id.try_as_ref() {
            Some(category) => Condition::all().add(posts::Column::CategoryId.eq(*category)),
            None => Condition::all(),
        }
    })
// "hello" can exist once per category

With sea-orm-soft-delete, scope to rows outside the trash, so a trashed post frees its slug:

.scope(|_| Condition::all().add(posts::Column::DeletedAt.is_null()))

Back it with a unique index

The slug is checked, then saved: two requests saving "Hello" at the same moment can both see hello as free. Add a unique index on the slug (with the scope columns, and WHERE deleted_at IS NULL for soft deletes) so the database refuses the second one, and retry that save:

manager
    .create_index(Index::create().name("posts_slug_unique").table(Posts::Table).col(Posts::Slug).unique().to_owned())
    .await?;

Options

use sea_orm_sluggable::SlugOptions;

SlugConfig::new([posts::Column::Title], posts::Column::Slug).options(
    SlugOptions::default()
        .separator("_")                                      // default "-"
        .max_length(100)                                     // default 250, cut before the suffix
        .suffix_start(2)                                     // default 1: "title", "title-1", ...
        .suffix_on_first(true)                               // default off: "title-1" even when free
        .suffix_with(|_slug, attempt| format!("v{attempt}")) // "title-v1" instead of "title-1"
        .reserved(["new", "edit", "feed"]),                  // default none
)

Reserved words

A post titled "New" must not take the slug new and shadow your /posts/new route. List the words your routes use, and such a slug gets a suffix instead (new-1). The comparison ignores case. The idea comes from Rails' FriendlyId.

Without a model

let slug = sea_orm_sluggable::slugify("Hello, World!", &SlugOptions::default());
let slug = sea_orm_sluggable::unique_slug::<posts::Entity, _>(&db, posts::Column::Slug, "Hello", &options).await?;

Languages

The default transliteration, AnyAscii, handles every script but knows no national rules. For those, enable a language feature:

sea-orm-sluggable = { version = "0.1", features = ["uk"] }
use sea_orm_sluggable::{languages::Ukrainian, SlugOptions};

let options = SlugOptions::default().transliterator(Ukrainian);
// "Юрій Яковенко" -> "yurii-yakovenko"   (AnyAscii alone: "yuriy-yakovenko")
Feature Language Rules
uk Ukrainian Cabinet of Ministers resolution No. 55 (2010)

Your own language

Implement Transliterator and pass it to SlugOptions::transliterator:

use sea_orm_sluggable::Transliterator;

struct Polish;

impl Transliterator for Polish {
    fn transliterate(&self, text: &str) -> String {
        // your table here
        text.to_string()
    }
}

Adding a language to the package

  1. Copy src/languages/uk.rs to src/languages/<code>.rs and replace the table.
  2. Add tests built from the official examples of your national standard.
  3. Add the feature to Cargo.toml and a #[cfg(feature = "<code>")] export in src/languages/mod.rs.
  4. Add a row to the table above and open a pull request.

Errors

fill_slug returns SlugError::Empty when the source has no letters or digits (for example "!!!"), and SlugError::Db when the uniqueness query fails. Inside before_save the ? turns both into DbErr.

Coming from Laravel

spatie/laravel-sluggable (v6) sea-orm-sluggable
#[Sluggable] / use HasSlug + getSlugOptions() impl Sluggable + fill_slug in before_save
from: 'title' / generateSlugsFrom('title') SlugConfig::new([Column::Title], ...)
to: 'slug' / saveSlugsTo('slug') SlugConfig::new(..., Column::Slug)
onUpdate: false the default; .on_update(true) to regenerate
preventOverwrite: true .prevent_overwrite(true)
skipGenerateWhen(fn) .skip_when(fn)
extraScope(fn) .scope(fn)
separator: '_' SlugOptions::separator("_")
maxLength: 100 SlugOptions::max_length(100)
startSlugSuffixFrom(2) SlugOptions::suffix_start(2)
useSuffixOnFirstOccurrence() SlugOptions::suffix_on_first(true)
usingSuffixGenerator(fn) SlugOptions::suffix_with(fn)
language: 'uk' SlugOptions::transliterator(Ukrainian)
Post::findBySlug($slug) find_by_slug::<posts::Entity, _>(...)
— SlugOptions::reserved([...])

Contributing

Issues and pull requests are welcome, language tables especially. The tests need no database server:

cargo test --all-features

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.


Made by AxVi · part of AxViLab