Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict'
- const slug = require('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.toLowerCase())
- 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
Add Comment
Please, Sign In to add comment