vendor slugs routes instead of ids
This commit is contained in:
30
lib/utils/slugify.ts
Normal file
30
lib/utils/slugify.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
export function slugify(text: string): string {
|
||||
return text
|
||||
.toString()
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/[^\w\-]+/g, '')
|
||||
.replace(/\-\-+/g, '-')
|
||||
.replace(/^-+/, '')
|
||||
.replace(/-+$/, '')
|
||||
}
|
||||
|
||||
export async function generateUniqueSlug(
|
||||
baseSlug: string,
|
||||
checkUnique: (slug: string) => Promise<boolean>,
|
||||
maxAttempts = 10
|
||||
): Promise<string> {
|
||||
let slug = baseSlug
|
||||
let attempt = 1
|
||||
|
||||
while (await checkUnique(slug)) {
|
||||
if (attempt >= maxAttempts) {
|
||||
throw new Error(`Could not generate unique slug after ${maxAttempts} attempts`)
|
||||
}
|
||||
slug = `${baseSlug}-${attempt}`
|
||||
attempt++
|
||||
}
|
||||
|
||||
return slug
|
||||
}
|
||||
Reference in New Issue
Block a user