Last active
August 29, 2015 14:16
-
-
Save lorenmh/57feb4ef572a123d0436 to your computer and use it in GitHub Desktop.
Sequelize unique slugify function. The model needs to have a slug and title field.
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
function toSlug(str) { | |
return str.replace(/[^\w\s\-]/g, ' ') | |
.split(' ') | |
.filter(function(substr) { | |
return (substr.length > 0); | |
}) | |
.join('-') | |
; | |
} | |
function slugify(Model) { | |
return function(instance, options, cb) { | |
if (instance.title !== undefined) { | |
var slug = instance.slug || toSlug( instance.title ); | |
Model.find({ where: { slug: slug } }).then( function(found) { | |
if (found === null) { | |
instance.slug = slug; | |
cb(null, instance); | |
} else { | |
var count = 1; | |
slug += '-'; | |
(function recursiveFindUniqueSlug() { | |
Model.find({ where: { slug: slug + count } }) | |
.then( function(found) { | |
if (found === null) { | |
instance.slug = slug + count; | |
cb(null, instance); | |
} else { | |
count++; | |
recursiveFindUniqueSlug(); | |
} | |
}); | |
})(); | |
} | |
}); | |
} else { | |
// if instance title isn't set then let the validation fail | |
cb(null, instance); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ex:
Blog.hook('beforeValidate', slugify(Blog));