implemented API create endpoint

+ added plugins to read json and access the header to parse the request
  for an API request
+ fixed logic where url param is nil
+ refactored the new code to a variable to be reused easier
+ if CONTENT_TYPE header is application/json, reply with json
- there could be more refactoring (maybe separating it to a different
  endpoint) to handle other scenarios, we'll work on that later
pull/21/head
Adam Townsend 2023-10-11 19:21:43 -07:00
parent 3ae20255f6
commit 4a82174526
1 changed files with 8 additions and 2 deletions

10
app.rb
View File

@ -7,6 +7,8 @@ class App < Roda
plugin :sessions, secret: ENV.delete('APP_SESSION_SECRET')
plugin :render, escape: true
plugin :flash
plugin :json_parser
plugin :request_headers
DB = Sequel.sqlite("db/#{ENV['DB_NAME']}")
links = DB[:links]
@ -27,7 +29,7 @@ class App < Roda
r.post "create" do
url = r.params['url']
if url.empty?
if url.nil? or url.empty?
flash['message'] = "Please enter a valid URL";
r.redirect '/'
end
@ -36,8 +38,12 @@ class App < Roda
links.insert(url: url, code: code)
@message = "Link created"
end
code = links.filter(:url => url).first[:code]
@message ||= "Link exists"
@new_link = 'http://' + request.env['HTTP_HOST'] + '/' + links.filter(:url => url).first[:code]
@new_link = 'http://' + request.env['HTTP_HOST'] + '/' + code
if 'application/json' == r.headers['CONTENT_TYPE']
return {url: url, code: code, link: @new_link}.to_json
end
view :create
end
end