No need to worry, I can give you the code for slugs, you can get it from Stackoverflow or just get it from the repo of the friendly-slugs. Here’s my version of it as a function:
name
is what you need a slug for and type
can be removed entirely or use it to put slugs in various places (Collections) with the same function.
I use this in onCreateUser. For best performance you would have a collection index on the slug field
const transliteration = [
{ from: 'àáâäåãа', to: 'a' },
{ from: 'б', to: 'b' },
{ from: 'ç', to: 'c' },
{ from: 'д', to: 'd' },
{ from: 'èéêëẽэе', to: 'e' },
{ from: 'ф', to: 'f' },
{ from: 'г', to: 'g' },
{ from: 'х', to: 'h' },
{ from: 'ìíîïи', to: 'i' },
{ from: 'к', to: 'k' },
{ from: 'л', to: 'l' },
{ from: 'м', to: 'm' },
{ from: 'ñн', to: 'n' },
{ from: 'òóôöõо', to: 'o' },
{ from: 'п', to: 'p' },
{ from: 'р', to: 'r' },
{ from: 'с', to: 's' },
{ from: 'т', to: 't' },
{ from: 'ùúûüу', to: 'u' },
{ from: 'в', to: 'v' },
{ from: 'йы', to: 'y' },
{ from: 'з', to: 'z' },
{ from: 'æ', to: 'ae' },
{ from: 'ч', to: 'ch' },
{ from: 'щ', to: 'sch' },
{ from: 'ш', to: 'sh' },
{ from: 'ц', to: 'ts' },
{ from: 'я', to: 'ya' },
{ from: 'ю', to: 'yu' },
{ from: 'ж', to: 'zh' },
{ from: 'ъь', to: '' }
]
const createUserSlug = (name, type) => {
const lowCaseStr = name.toLowerCase()
let slug = lowCaseStr
.replace(/'/g, '') // Remove all apostrophes
.replace(/[^0-9a-z.]/g, '') // Remove anything that is not 0-9, a-z, dot
/* eslint-disable */
.replace(/\-\-+/g, '') // Remove multiple -
/* eslint-enable */
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, '') // Trim - from end of text
transliteration.map(item => {
slug = slug.replace(new RegExp('[' + item.from + ']', 'g'), item.to)
})
if (type === 'user') {
if (Meteor.users.findOne({ slug })) {
do {
const randomIndex = Math.floor(Math.random() * 9) + 1
slug = slug + randomIndex.toString()
}
while (Meteor.users.findOne({ slug }))
}
return slug
} else if (type === 'org') {
if (Organizations.findOne({ slug })) {
do {
const randomIndex = Math.floor(Math.random() * 9) + 1
slug = slug + randomIndex.toString()
}
while (Organizations.findOne({ slug }))
}
return slug
} else if (type === 'school') {
if (Schools.findOne({ slug })) {
do {
const randomIndex = Math.floor(Math.random() * 9) + 1
slug = slug + randomIndex.toString()
}
while (Schools.findOne({ slug }))
}
return slug
}
}