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