Guest User

Untitled

a guest
Oct 21st, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. 'use strict'
  2.  
  3. const slug = require('slug')
  4.  
  5. class Slugify {
  6.  
  7. register (model) {
  8.  
  9. const source = model.sluggable.source
  10. const key = model.sluggable.key
  11.  
  12. model.addHook('beforeCreate', function * (next) {
  13. this[key] = yield Slugify.generateUniqueSlug(model, key, this[source])
  14. yield next
  15. })
  16.  
  17. }
  18.  
  19. static * generateUniqueSlug (model, key, source) {
  20. const generatedSlug = slug(source.toLowerCase())
  21. const matchingSlug = yield model.query()
  22. .where(key, generatedSlug)
  23. .orWhere(key, 'like', `${generatedSlug}%`)
  24. .orderBy(model.primaryKey, 'desc')
  25. .first()
  26.  
  27. if (!matchingSlug || !matchingSlug.slug) {
  28. return generatedSlug
  29. }
  30.  
  31. return `${generatedSlug}-${Slugify.nextIndex(generatedSlug, matchingSlug.slug)}`
  32. }
  33.  
  34. static nextIndex (generatedSlug, latestSlug) {
  35. if (generatedSlug === latestSlug) {
  36. return 1
  37. }
  38.  
  39. const parts = latestSlug.split('-')
  40.  
  41. return parseInt(parts[parts.length - 1]) + 1
  42. }
  43.  
  44. }
  45.  
  46. module.exports = Slugify
Add Comment
Please, Sign In to add comment