-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathapi.rb
75 lines (63 loc) · 1.73 KB
/
api.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
require 'sinatra'
require 'sqlite3'
require "multi_json"
require "sinatra/multi_route"
require 'active_record'
require_relative 'helpers'
require_relative 'model'
ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'w'))
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => 'usdadb_new.sqlite3'
)
class UsdaAPI < Sinatra::Application
set :protection, :except => [:json_csrf]
before do
# set headers
headers 'Content-Type' => 'application/json; charset=utf8'
headers 'Access-Control-Allow-Methods' => 'HEAD, GET'
headers 'Access-Control-Allow-Origin' => '*'
cache_control :public, :must_revalidate, max_age: 60
end
# prohibit certain methods
route :put, :post, :delete, :copy, :options, :trace, '/*' do
halt 405
end
# handle missed route
not_found do
halt 404, MultiJson.dump({ error: 'route not found' })
end
# handle other errors
error do
halt 500, MultiJson.dump({ error: 'server error' })
end
# default to heartbeat
get '/?' do
redirect '/heartbeat/'
end
get "/heartbeat/?" do
return MultiJson.dump({
"routes" => [
"/search (HEAD, GET)",
"/heartbeat"
]
})
end
get '/search/?' do
get_data_ar
end
# helpers --------
def get_data_ar
begin
data = Usda.endpoint(params)
raise Exception.new('no results found') if data.length.zero?
{ count: data.limit(nil).count(1), returned: data.length,
citation: $usda_citation, terms: $usda_terms,
data: data, error: nil }.to_json
rescue Exception => e
halt 400, { count: 0, returned: 0, data: nil,
citation: $usda_citation, terms: $usda_terms,
error: { message: e.message } }.to_json
end
end
end