frankfurter/lib/api.rb

75 lines
1.2 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
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'
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).attributes.tap do |data|
data[:rates].keep_if { |k, _| symbols.include?(k) } if symbols
2012-11-23 15:27:09 +01:00
end
2016-04-11 15:26:49 +02:00
rescue Quote::Invalid => ex
halt 422, encode_json(error: ex.message)
2015-09-15 13:00:57 +02:00
end
def symbols
2016-04-25 19:59:07 +02:00
@symbols ||= params.values_at('symbols', 'currencies').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
2012-11-20 17:36:12 +01:00
end
use Rack::Cors do
allow do
origins '*'
resource '*'
end
end
options '*' do
2016-04-25 20:05:07 +02:00
200
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
2015-09-15 13:01:16 +02:00
last_modified quote[:date]
2015-08-30 12:54:13 +02:00
jsonp quote
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
2015-09-15 13:01:16 +02:00
last_modified quote[:date]
2015-08-30 12:54:13 +02:00
jsonp quote
2012-11-23 15:13:49 +01:00
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