This plugin will automatically generate slugs for your model based on a source field and a slug field. It will also generate unique slugs by checking to see if the slug already exists in the model's table.
npm install objection-slugify --save
// Import the plugin.
const slugifyPlugin = require('objection-slugify');
const { Model } = require('objection');
// Mixin the plugin.
const slugify = slugifyPlugin({
sourceField: 'title',
slugField: 'slug'
});
// Create your model.
class Post extends slugify(Model) {
// ...code
}
const post = await Post.query().insert({
title: 'How to Fry an Egg'
});
console.log(post.slug);
// how-to-fry-an-egg
The source of the slugged content.
The field to store the slug on.
Specifies whether the slug is updated when the source field is updated.
Checks to see if the generated slug is unique in the table. If not, it will append a UUID to the end of the slug.
A custom function that returns a string. Can be used to generate a custom suffix
to the end of the slug. If unique
is true and this is not specified, a random
UUID will be appended to the slug.
A set of options for the internal slugify library, options available here.