frankfurter/lib/web/server.rb

97 lines
2.1 KiB
Ruby
Raw Normal View History

2015-12-30 20:52:02 +01:00
# frozen_string_literal: true
2017-06-14 22:16:21 +02:00
require 'oj'
require 'rack/contrib/jsonp'
require 'rack/cors'
require 'roda'
2018-10-10 14:39:25 +02:00
require 'currency_names'
require 'query'
2018-04-16 17:19:15 +02:00
require 'quote'
2012-11-20 17:36:12 +01:00
module Web
class Server < Roda
use Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: %i[get options]
end
end
use Rack::JSONP
2017-01-03 14:37:40 +01:00
plugin :caching
2015-05-25 13:12:35 +02:00
2022-03-07 13:02:12 +01:00
plugin :halt
plugin :error_handler do |error|
request.halt 422, { message: error.message }
end
2014-05-01 12:56:28 +02:00
plugin :indifferent_params
plugin :json, content_type: 'application/json; charset=utf-8',
serializer: ->(o) { Oj.dump(o, mode: :compat) }
2018-09-25 15:52:33 +02:00
plugin :params_capturing
route do |r|
2023-03-01 15:28:18 +01:00
response.cache_control public: true, max_age: 900
r.root do
{ docs: 'https://www.frankfurter.app/docs' }
end
r.is(/latest|current/) do
r.params['date'] = Date.today.to_s
quote = quote_end_of_day(r)
r.etag quote.cache_key
quote.formatted
end
r.is(/(\d{4}-\d{2}-\d{2})/) do
r.params['date'] = r.params['captures'].first
quote = quote_end_of_day(r)
r.etag quote.cache_key
2018-04-16 17:19:15 +02:00
quote.formatted
end
r.is(/(\d{4}-\d{2}-\d{2})\.\.(\d{4}-\d{2}-\d{2})?/) do
r.params['start_date'] = r.params['captures'].first
r.params['end_date'] = r.params['captures'][1] || Date.today.to_s
quote = quote_interval(r)
r.etag quote.cache_key
2014-06-19 13:31:35 +02:00
quote.formatted
end
2012-11-20 20:32:26 +01:00
r.is 'currencies' do
currency_names = CurrencyNames.new
r.etag currency_names.cache_key
2018-04-16 17:19:15 +02:00
currency_names.formatted
end
end
private
2018-10-10 14:39:25 +02:00
def quote_end_of_day(request)
query = Query.build(request.params)
quote = Quote::EndOfDay.new(**query)
quote.perform
2022-03-07 13:02:12 +01:00
request.halt 404, { message: 'not found' } if quote.not_found?
quote
end
def quote_interval(request)
query = Query.build(request.params)
quote = Quote::Interval.new(**query)
quote.perform
2022-03-07 13:02:12 +01:00
request.halt 404, { message: 'not found' } if quote.not_found?
quote
end
end
end