Skip to content

Instantly share code, notes, and snippets.

@lorenmh
Last active August 29, 2015 14:16
Show Gist options
  • Save lorenmh/57feb4ef572a123d0436 to your computer and use it in GitHub Desktop.
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.
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);
}
};
}
@lorenmh
Copy link
Author

lorenmh commented Mar 10, 2015

ex: Blog.hook('beforeValidate', slugify(Blog));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment