forked from PeopleAndCode/csv-to-mongo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.rb
90 lines (71 loc) · 1.74 KB
/
connection.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
require 'typhoeus'
require 'uri'
require 'json'
require "#{File.dirname(__FILE__)}/mongo/request.rb"
module OpenData
module Connection
def get(options={})
connect(:get, options)
end
def post(options={})
connect(:post, options)
end
def put(options={})
connect(:put, options)
end
def delete(options={})
connect(:delete, options)
end
private
def connect(method, options={})
adapter = options[:adapter] ||= :mongo
adapter = adapter.downcase.to_sym
if adapter === :rest
rest_connect(method, options)
else
mongo_connect(method, options)
end
end
def mongo_connect(method=:get, options={})
path = options[:path]
document = options[:body] ||= nil
options = {
method: method,
document: document
}
request = OpenData::Mongo::Request.new(path, options)
request.run
end
def rest_connect(method=:get, options={})
apikey = ENV['MONGO_APIKEY']
url = "https://api.mongohq.com/"
url = "#{url}#{options[:path]}?_apikey=#{apikey}"
if options[:body]
body = {}
body[:document] = options[:body]
body = body.to_json
else
body = nil
end
params = {}
if options[:params]
params.merge!(options[:params])
end
headers = {
:"Content-Type" => "application/json",
:Accept => "application/json"
}
if options[:headers]
headers.merge!(options[:headers])
end
request = Typhoeus::Request.new(
url,
method: method,
body: body,
params: params,
headers: headers
)
request.run
end
end
end