-
Notifications
You must be signed in to change notification settings - Fork 0
/
presence.rb
81 lines (70 loc) · 1.71 KB
/
presence.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
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'json/ext' # required for .to_json
require 'json'
require 'pry'
require 'dotenv'
Dotenv.load
configure do
db = Mongo::Client.new( ENV['MONGO_URI'])
set :pings_db, db[:pings]
set :counts_db, db[:counts]
end
helpers do
# a helper method to turn a string ID
# representation into a BSON::ObjectId
def object_id val
begin
BSON::ObjectId.from_string(val)
rescue BSON::ObjectId::Invalid
nil
end
end
def document_by_id id
id = object_id(id) if String === id
if id.nil?
{}.to_json
else
document = settings.pings_db.find(:_id => id).to_a.first
(document || {}).to_json
end
end
end
get '/' do
"Set your Cloudtrax Presence Reporting Server Location to: <br/>#{request.base_url}/ping"
end
get '/collections/?' do
content_type :json
settings.pings_db.database.collection_names.to_json
end
get '/collect_counts' do
content_type :json
settings.pings_db.distinct("network_id").each do |nid|
binding.pry
doc = {network_id: nid,
count: settings.pings_db.find({ network_id: nid}).count
}
settings.counts_db.insert_one doc
end
end
# list all documents in the test collection
get '/pings/?' do
content_type :json
settings.pings_db.find.to_a.to_json
end
# find a document by its ID
get '/pings/:id/?' do
content_type :json
document_by_id(params[:id])
end
# insert a new document from the request parameters,
# then return the full document
post '/ping/?' do
params = JSON.parse request.body.read
params[:timestamp] = Time.now.to_i
content_type :json
db = settings.pings_db
result = db.insert_one params
db.find(:_id => result.inserted_id).to_a.first.to_json
end