Skip to content

Instantly share code, notes, and snippets.

@RomainLanz
Last active November 11, 2017 11:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RomainLanz/a958fff2f41ad85994f5211b1ab27ca3 to your computer and use it in GitHub Desktop.
Save RomainLanz/a958fff2f41ad85994f5211b1ab27ca3 to your computer and use it in GitHub Desktop.
'use strict'
const slug = require('@slynova/slug')
class Slugify {
register (model) {
const source = model.sluggable.source
const key = model.sluggable.key
model.addHook('beforeCreate', function * (next) {
this[key] = yield Slugify.generateUniqueSlug(model, key, this[source])
yield next
})
}
static * generateUniqueSlug (model, key, source) {
const generatedSlug = slug(source)
const matchingSlug = yield model.query()
.where(key, generatedSlug)
.orWhere(key, 'like', `${generatedSlug}%`)
.orderBy(model.primaryKey, 'desc')
.first()
if (!matchingSlug || !matchingSlug.slug) {
return generatedSlug
}
return `${generatedSlug}-${Slugify.nextIndex(generatedSlug, matchingSlug.slug)}`
}
static nextIndex (generatedSlug, latestSlug) {
if (generatedSlug === latestSlug) {
return 1
}
const parts = latestSlug.split('-')
return parseInt(parts[parts.length - 1]) + 1
}
}
module.exports = Slugify
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment