32 lines
752 B
TypeScript
32 lines
752 B
TypeScript
import { v7 as uuidv7 } from 'uuid';
|
|
|
|
export function slugify(value: string): string {
|
|
return value
|
|
.normalize('NFD')
|
|
.replace(/[\u0300-\u036f]/g, '')
|
|
.toLowerCase()
|
|
.trim()
|
|
.replace(/[^a-z0-9\s-]/g, '')
|
|
.replace(/\s+/g, '-')
|
|
.replace(/-+/g, '-');
|
|
}
|
|
|
|
export async function buildUniqueSlug(
|
|
source: string,
|
|
findExisting: (slug: string) => Promise<{ id: string } | null>
|
|
): Promise<string> {
|
|
const base = slugify(source);
|
|
const fallback = base.length > 0 ? base : `resource-${uuidv7().slice(0, 8)}`;
|
|
|
|
let candidate = fallback;
|
|
let index = 1;
|
|
|
|
while (true) {
|
|
const existing = await findExisting(candidate);
|
|
if (!existing) return candidate;
|
|
|
|
index += 1;
|
|
candidate = `${fallback}-${index}`;
|
|
}
|
|
}
|