Skip to content

Commit

Permalink
fix: generate slug by user + check existing link on update
Browse files Browse the repository at this point in the history
  • Loading branch information
sjdonado committed Jul 31, 2024
1 parent afa9b33 commit d0ae9d8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
15 changes: 13 additions & 2 deletions app/controllers/link.cr
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ module App::Controllers::Link
link.id = UUID.v4.to_s
link.url = url
link.user = user
link.slug = SlugService.shorten_url(url)
link.slug = SlugService.shorten_url(url, user.id.to_s)

changeset = Database.insert(link)
if !changeset.valid?
Expand Down Expand Up @@ -118,6 +118,7 @@ module App::Controllers::Link
class Update < App::Lib::BaseController
include App::Models
include App::Lib
include App::Services

def call(env)
user = env.get("user").as(User)
Expand All @@ -130,7 +131,17 @@ module App::Controllers::Link
raise App::NotFoundException.new(env) if link.nil?
raise App::ForbiddenException.new(env) if link.user_id != user.id

link.url = body["url"].to_s
new_url = body["url"].to_s

existing_query = Database::Query.where(url: new_url, user_id: user.id.to_s).limit(1)
existing_link = Database.all(Link, existing_query).first?

if existing_link
raise App::UnprocessableEntityException.new(env, { "url" => ["URL already exists"] })
end

link.url = new_url
link.slug = SlugService.shorten_url(new_url, user.id.to_s)

changeset = Database.update(link)
if !changeset.valid?
Expand Down
5 changes: 3 additions & 2 deletions app/services/slug.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ require "digest"
require "base64"

module App::Services::SlugService
def self.shorten_url(url : String) : String
crc32_hash = Digest::CRC32.digest(url)
def self.shorten_url(url : String, user_id : String) : String
combined = "#{user_id}-#{url}"
crc32_hash = Digest::CRC32.digest(combined)
base62_encoded = Base64.urlsafe_encode(crc32_hash).strip.tr("-_=", "")

base62_encoded
Expand Down

0 comments on commit d0ae9d8

Please sign in to comment.