Compare commits

..

4 Commits

Author SHA1 Message Date
Adam Townsend 4a82174526 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
2023-10-11 19:21:43 -07:00
Adam Townsend 3ae20255f6 DRY it out a little 2023-10-11 19:21:21 -07:00
Adam Townsend f69c53bf29 removed unnecessary variable 2023-10-11 19:20:07 -07:00
Adam Townsend 7d6c098047 added more to the spec test for creating a new link 2023-10-11 19:18:47 -07:00
2 changed files with 16 additions and 4 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

View File

@ -14,8 +14,14 @@ end
describe "Submit API request to create new link" do
include Rack::Test::Methods
it "should return link data in json format" do
post '/create'
last_response.should be_ok
data = {
url: 'http://google.com'
}
post('/create', data.to_json, "CONTENT_TYPE" => "application/json")
expect(last_response).to be_ok
response_json = JSON.parse(last_response.body)
expect(response_json['url']).to eq(data[:url])
expect(response_json['code']).not_to eq(nil)
end
end