From 4a821745264afaf9c2c6c83fb301ff3565e19ed9 Mon Sep 17 00:00:00 2001 From: Adam Townsend Date: Wed, 11 Oct 2023 19:21:43 -0700 Subject: [PATCH] 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 --- app.rb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app.rb b/app.rb index 2e49f5e..cd7c2b0 100644 --- a/app.rb +++ b/app.rb @@ -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