-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.rb
More file actions
106 lines (76 loc) · 1.9 KB
/
app.rb
File metadata and controls
106 lines (76 loc) · 1.9 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
require "sinatra"
require "sinatra/json"
require "json"
require_relative "./game.rb"
if ENV["PORT"]
set :port, ENV["PORT"]
end
configure do
enable :cross_origin
end
before do
response.headers["Access-Control-Allow-Origin"] = "*"
end
options "*" do
response.headers["Allow"] = "GET, PUT, POST, DELETE, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type, Accept, X-User-Email, X-Auth-Token"
response.headers["Access-Control-Allow-Origin"] = "*"
200
end
get "/" do
send_file File.join(settings.public_folder, "index.html")
end
post "/games/?" do
data = parse_body
# Remove all the old games.
# This makes sure that we do not fill the database
Game.where("created_at < ?", Date.today - 3).delete_all
game = Game.create(difficulty: data["difficulty"].to_i, state: "new")
status 201
json(game)
end
get "/games/{id}/?" do
data = parse_body
game = Game.find(data["id"])
json(game)
end
post "/games/{id}/flag/?" do
data = parse_body
game = Game.find(data["id"])
validate_move(data, game)
game.flag(data["row"].to_i, data["col"].to_i)
game.save
json(game)
end
post "/games/{id}/check/?" do
data = parse_body
game = Game.find(data["id"])
validate_move(data, game)
game.check(data["row"].to_i, data["col"].to_i)
game.save
json(game)
end
def validate_move(data, game)
if data["row"].nil?
halt 400, json({ error: "Missing parameter row" })
end
if data["col"].nil?
halt 400, json({ error: "Missing parameter col" })
end
row = data["row"].to_i
col = data["col"].to_i
if game.out_of_bounds?(row, col)
halt 400, json({ error: "Illegal move" })
end
end
def parse_body
data = nil
begin
body = request.body.read
data = body.empty? ? {} : JSON.parse(body)
rescue JSON::ParserError
halt 400, json(error: "Sorry, your JSON request could not be parsed")
end
data.merge!(params)
data
end