frankfurter/lib/api.rb

98 lines
1.6 KiB
Ruby
Raw Normal View History

2015-12-30 20:52:02 +01:00
# frozen_string_literal: true
require 'oj'
2012-11-20 17:36:12 +01:00
require 'sinatra'
require 'rack/cors'
2015-08-30 12:54:13 +02:00
require 'quote'
2012-11-20 17:36:12 +01:00
2017-01-03 14:37:40 +01:00
set :cache_ttl, 900 # 15 minutes
2015-05-25 13:12:35 +02:00
configure :development do
set :show_exceptions, :after_handler
end
2014-05-01 12:56:28 +02:00
configure :production do
require 'newrelic_rpm'
2017-01-04 12:19:00 +01:00
disable :dump_errors
2014-05-01 12:56:28 +02:00
end
2012-11-21 12:31:50 +01:00
helpers do
2015-08-30 12:54:13 +02:00
def quote
@quote ||= Quote.new(params)
end
def quote_attributes
@quote_attributes ||= quote.attributes.tap do |data|
data[:rates].keep_if { |k, _| symbols.include?(k) } if symbols
2012-11-23 15:27:09 +01:00
end
end
2015-09-15 13:00:57 +02:00
def symbols
2016-10-12 00:37:29 +02:00
@symbols ||= params.values_at('symbols', 'to').compact.first
2012-11-21 12:31:50 +01:00
end
def jsonp(data)
json = encode_json(data)
callback = params.delete('callback')
if callback
content_type :js
"#{callback}(#{json})"
else
content_type :json
json
end
2014-03-17 11:10:39 +01:00
end
def encode_json(data)
Oj.dump(data, mode: :compat)
end
2017-01-03 14:37:40 +01:00
def cache
App.cache.fetch request.fullpath, settings.cache_ttl do
yield
end
end
2012-11-20 17:36:12 +01:00
end
use Rack::Cors do
allow do
origins '*'
2017-01-04 12:18:31 +01:00
resource '*', headers: :any, methods: :get
end
end
options '*' do
2016-04-25 20:05:07 +02:00
200
end
before do
content_type 'application/json'
end
2014-06-19 13:31:35 +02:00
get '/' do
last_modified App.released_at
2015-05-25 13:12:35 +02:00
jsonp details: 'http://fixer.io', version: App.version
2014-06-19 13:31:35 +02:00
end
2012-11-20 17:36:12 +01:00
get '/latest' do
2017-01-03 14:37:40 +01:00
cache do
last_modified quote_attributes[:date]
jsonp quote_attributes
end
2012-11-20 17:36:12 +01:00
end
2012-11-20 20:32:26 +01:00
2016-04-11 15:26:49 +02:00
get(/(?<date>\d{4}-\d{2}-\d{2})/) do
2017-01-03 14:37:40 +01:00
cache do
last_modified quote_attributes[:date]
jsonp quote_attributes
end
end
2014-03-17 11:10:39 +01:00
not_found do
halt 404, encode_json(error: 'Not found')
2014-03-17 11:10:39 +01:00
end
error Quote::Invalid do |ex|
halt 422, encode_json(error: ex.message)
end