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 laterpull/21/head
parent
3ae20255f6
commit
4a82174526
10
app.rb
10
app.rb
|
|
@ -7,6 +7,8 @@ class App < Roda
|
||||||
plugin :sessions, secret: ENV.delete('APP_SESSION_SECRET')
|
plugin :sessions, secret: ENV.delete('APP_SESSION_SECRET')
|
||||||
plugin :render, escape: true
|
plugin :render, escape: true
|
||||||
plugin :flash
|
plugin :flash
|
||||||
|
plugin :json_parser
|
||||||
|
plugin :request_headers
|
||||||
|
|
||||||
DB = Sequel.sqlite("db/#{ENV['DB_NAME']}")
|
DB = Sequel.sqlite("db/#{ENV['DB_NAME']}")
|
||||||
links = DB[:links]
|
links = DB[:links]
|
||||||
|
|
@ -27,7 +29,7 @@ class App < Roda
|
||||||
|
|
||||||
r.post "create" do
|
r.post "create" do
|
||||||
url = r.params['url']
|
url = r.params['url']
|
||||||
if url.empty?
|
if url.nil? or url.empty?
|
||||||
flash['message'] = "Please enter a valid URL";
|
flash['message'] = "Please enter a valid URL";
|
||||||
r.redirect '/'
|
r.redirect '/'
|
||||||
end
|
end
|
||||||
|
|
@ -36,8 +38,12 @@ class App < Roda
|
||||||
links.insert(url: url, code: code)
|
links.insert(url: url, code: code)
|
||||||
@message = "Link created"
|
@message = "Link created"
|
||||||
end
|
end
|
||||||
|
code = links.filter(:url => url).first[:code]
|
||||||
@message ||= "Link exists"
|
@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
|
view :create
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue