Initial commit
This commit is contained in:
commit
63ee71a19b
123 files changed
+11268
No files matched your search
@@ -0,0 +1,42 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user