From ac3e9f14cd5824f10750fd5a705beed3ef387663 Mon Sep 17 00:00:00 2001 From: Adam Townsend Date: Thu, 12 Oct 2023 11:42:43 -0700 Subject: [PATCH] added links route for API interactions --- app.rb | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/app.rb b/app.rb index cd7c2b0..5bd4ef7 100644 --- a/app.rb +++ b/app.rb @@ -41,10 +41,29 @@ class App < Roda code = links.filter(:url => url).first[:code] @message ||= "Link exists" @new_link = 'http://' + request.env['HTTP_HOST'] + '/' + code - if 'application/json' == r.headers['CONTENT_TYPE'] + view :create + end + r.on "links" do + r.post do + if 'application/json' != r.headers['CONTENT_TYPE'] + return {message: "Not a valid JSON request"}.to_json + end + + url = r.params['url'] + if url.nil? or url.empty? + response.status = 400 + return {message: "Please enter a valid URL"} + end + + if links.filter(:url => url).first.nil? + code = SecureRandom.urlsafe_base64 4 + links.insert(url: url, code: code) + end + + code = links.filter(:url => url).first[:code] + @new_link = 'http://' + request.env['HTTP_HOST'] + '/' + code return {url: url, code: code, link: @new_link}.to_json end - view :create end end end