-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.rb
91 lines (69 loc) · 1.62 KB
/
app.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
91
require "sinatra"
require "sinatra/json"
require "json"
require "amazing_print"
set(:port, ENV["PORT"]) if ENV["PORT"]
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
require_relative "./moves.rb"
require_relative "./game.rb"
get "/" do
send_file File.join(settings.public_folder, "docs.html")
end
post "/game" do
game = Game.new_game
json(game)
end
get "/game/:id" do
id = params[:id]
game = Game.find_by(id: id)
if game
json(game)
else
status 404
end
end
post "/game/:id" do
request.body.rewind
data = nil
begin
data = JSON.parse(request.body.read)
rescue JSON::ParserError
halt 400, json(error: "Sorry, your JSON request could not be parsed")
end
id = params[:id]
column = data["column"]
row = data["row"]
unless ["0", "1", "2"].include?(column.to_s)
halt 400, json(error: "The value #{column || "null"} is invalid for the parameter column")
end
unless ["0", "1", "2"].include?(column.to_s)
halt 400, json(error: "The value #{row || "null"} is invalid for the parameter row")
end
game = Game.find_by(id: id)
unless game
status 404
return
end
if game.winner
json(game)
return
end
result = game.human_move(row.to_i, column.to_i)
if result == :invalid
status 400
return
end
game.save
json(game)
end