refactor: replace slug generation with CRC32 + base62

This commit is contained in:
Juan Rodriguez
2024-07-31 21:38:36 +02:00
parent d039add340
commit 6fc48dae83
2 changed files with 7 additions and 14 deletions
+1 -10
View File
@@ -27,16 +27,7 @@ module App::Controllers::Link
link.id = UUID.v4.to_s
link.url = url
link.user = user
attempts = 0
loop do
slug = SlugService.generate_base64(url, 5 + attempts)
unless Database.get_by(Link, slug: slug)
link.slug = slug
break
end
attempts += 1
end
link.slug = SlugService.shorten_url(url)
changeset = Database.insert(link)
if !changeset.valid?
+6 -4
View File
@@ -1,9 +1,11 @@
require "digest"
require "base64"
module App::Services::SlugService
def self.generate_base64(link : String, size : Int32) : String
hash = Digest::SHA256.digest(link)
base64_encoded = Base64.urlsafe_encode(hash).strip.tr("+/", "")
base64_encoded[0, size]
def self.shorten_url(url : String) : String
crc32_hash = Digest::CRC32.digest(url)
base62_encoded = Base64.urlsafe_encode(crc32_hash).strip.tr("-_=", "")
base62_encoded
end
end