frankfurter/lib/api.rb

76 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
2017-01-09 02:30:24 +01:00
use Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: :get
end
end
2017-01-03 14:37:40 +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'
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 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
end
options '*' do
2016-04-25 20:05:07 +02:00
200
end
2017-01-09 02:30:24 +01:00
get '*' do
cache_control :public, :must_revalidate, max_age: 900
pass
end
2014-06-19 13:31:35 +02:00
get '/' do
2017-01-09 02:30:24 +01:00
etag App.version
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-09 02:30:24 +01:00
last_modified quote.date
2017-01-10 13:44:22 +01:00
jsonp quote.to_h
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-09 02:30:24 +01:00
last_modified quote.date
2017-01-10 13:44:22 +01:00
jsonp quote.to_h
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