-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.rb
More file actions
73 lines (55 loc) · 1.48 KB
/
app.rb
File metadata and controls
73 lines (55 loc) · 1.48 KB
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
require "sinatra"
require "mongo"
require "json"
get "/" do
File.read(File.join("public", "index.html"))
end
before "/api/*" do
content_type :json
connection = Mongo::Connection.new("flame.mongohq.com", 27107)
db = connection.db(ENV["db"])
db.authenticate("heroku", ENV["heroku"])
@commanders = db.collection("commanders")
end
def replaceProp(hash, origProp, newProp)
hash[newProp] = hash[origProp].to_s
hash.delete(origProp)
end
get "/api/commanders" do
commanders = @commanders.find().to_a
commanders.each do |c|
c["votes"] = c["upvotes"].to_i - c["downvotes"].to_i
replaceProp(c, "_id", "id")
end
commanders.sort! { |a,b| b["votes"] <=> a["votes"] }
commanders.to_json
end
get "/api/commanders/:id" do
commander = @commanders.find_one(:_id => BSON::ObjectId(params[:id]))
if commander.count > 0
replaceProp(commander, "_id", "id")
end
commander.to_json
end
post "/api/commanders" do
body = JSON.parse(request.body.read)
id = @commanders.insert(body).to_s
replaceProp(body, "_id", "id")
body.to_json
end
put "/api/commanders/:id" do
id = BSON::ObjectId(params[:id])
p = params
commander = @commanders.find_one(:_id => id)
if p["like"]
commander["upvotes"] = commander["upvotes"].to_i + 1
else
commander["downvotes"] = commander["downvotes"].to_i + 1
end
@commanders.update({ :_id => id }, commander);
replaceProp(commander, "_id", "id")
commander.to_json
end
delete "/api/commanders/:id" do
#@commanders.remove(:_id => BSON::ObjectId(params[:id]))
end