43 lines
1.2 KiB
C#
43 lines
1.2 KiB
C#
using System.Text.RegularExpressions;
|
|
|
|
namespace OnlyPrompt.Backend.Utils
|
|
{
|
|
public static class SlugHelper
|
|
{
|
|
private static readonly Regex InvalidCharacters = new(@"[^a-z0-9\-]", RegexOptions.Compiled);
|
|
private static readonly Regex MultipleDashes = new(@"-+", RegexOptions.Compiled);
|
|
|
|
public static string GenerateSlug(string input, int? maxLength = null)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(input))
|
|
return string.Empty;
|
|
|
|
var slug = input.ToLowerInvariant().Replace(" ", "-").Replace("_", "-");
|
|
slug = InvalidCharacters.Replace(slug, string.Empty);
|
|
slug = MultipleDashes.Replace(slug, "-");
|
|
slug = slug.Trim('-');
|
|
if (maxLength.HasValue)
|
|
slug = slug.Limit(maxLength.Value);
|
|
|
|
return slug;
|
|
}
|
|
|
|
private const string SuffixChars = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
public static async Task<string> GenerateUniqueSlugAsync(string input, Func<string, Task<bool>> existsFunc, int? maxLenght)
|
|
{
|
|
var slug = GenerateSlug(input);
|
|
var exists = await existsFunc(slug);
|
|
if (exists)
|
|
{
|
|
var suffix = Random.Shared.GetString(8, SuffixChars);
|
|
if (maxLenght.HasValue)
|
|
slug = slug.Limit(maxLenght.Value - 9);
|
|
|
|
slug = $"{slug}-{suffix}";
|
|
}
|
|
|
|
return slug;
|
|
}
|
|
}
|
|
}
|