Last active
November 11, 2017 11:57
-
-
Save RomainLanz/a958fff2f41ad85994f5211b1ab27ca3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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