refactor: replace slug generation with CRC32 + base62
This commit is contained in:
+1
-10
@@ -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?
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user