feat: redirect by slug
This commit is contained in:
+2
-1
@@ -1 +1,2 @@
|
||||
DATABASE_URL=./sqlite/db.sqlite
|
||||
DATABASE_URL=sqlite3://./sqlite/data.db
|
||||
APP_URL=http://localhost:3000
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +micrate Up
|
||||
-- SQL in section 'Up' is executed when this migration is applied
|
||||
CREATE INDEX IF NOT EXISTS index_links_slug ON links (slug);
|
||||
|
||||
-- +micrate Down
|
||||
-- SQL in section 'Down' is executed when this migration is rolled back
|
||||
DROP INDEX IF EXISTS index_links_slug;
|
||||
+24
-3
@@ -6,10 +6,12 @@ module App::Controllers::Link
|
||||
include App::Lib
|
||||
|
||||
def call(env)
|
||||
params = env.params.json["link"].as(Hash)
|
||||
json_params = env.params.json.to_h
|
||||
url = json_params.has_key?("url") ? json_params["url"] : nil
|
||||
raise App::BadRequestException.new(env) if !url #TODO: return url "required field" error message
|
||||
|
||||
link = Link.new
|
||||
link.url = params["url"].as_s
|
||||
link.url = url.to_s
|
||||
link.slug = Random::Secure.urlsafe_base64(4)
|
||||
|
||||
changeset = Database.insert(link)
|
||||
@@ -19,7 +21,26 @@ module App::Controllers::Link
|
||||
raise App::UnprocessableEntityException.new(env, errors.to_json)
|
||||
end
|
||||
|
||||
App::Serializers::Link.new(link).to_json
|
||||
response = {"data" => App::Serializers::Link.new(link) }
|
||||
response.to_json
|
||||
end
|
||||
end
|
||||
|
||||
class Index < App::Lib::BaseController
|
||||
include App::Models
|
||||
include App::Lib
|
||||
|
||||
def call(env)
|
||||
slug = env.params.url["slug"]
|
||||
|
||||
link = Database.get_by(Link, slug: slug)
|
||||
raise App::NotFoundException.new(env) if !link
|
||||
|
||||
#TODO: update click_counter
|
||||
|
||||
env.redirect link.url!
|
||||
end
|
||||
end
|
||||
|
||||
#TODO: update, delete, list links
|
||||
end
|
||||
|
||||
+2
-9
@@ -1,16 +1,9 @@
|
||||
require "kemal"
|
||||
|
||||
module App
|
||||
class UnauthorizedException < Kemal::Exceptions::CustomException
|
||||
class BadRequestException < Kemal::Exceptions::CustomException
|
||||
def initialize(context)
|
||||
context.response.status_code = 401
|
||||
super(context)
|
||||
end
|
||||
end
|
||||
|
||||
class ForbiddenException < Kemal::Exceptions::CustomException
|
||||
def initialize(context)
|
||||
context.response.status_code = 403
|
||||
context.response.status_code = 400
|
||||
super(context)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -9,6 +9,10 @@ module App
|
||||
Controllers::Ping::Get.new.call(env)
|
||||
end
|
||||
|
||||
get "/:slug" do |env|
|
||||
Controllers::Link::Index.new.call(env)
|
||||
end
|
||||
|
||||
post "/api/links" do |env|
|
||||
Controllers::Link::Create.new.call(env)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user