-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathserver.gb
105 lines (92 loc) · 2.34 KB
/
server.gb
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
require "net/simple_server"
require "json"
require_relative "model"
server = Net::SimpleServer.new(ENV["PORT"] || "3000")
server.static("/icon/", "./public/icon/")
server.static("/js/", "./public/js/")
server.static("/css/", "./public/css/")
server.static("/font/", "./public/font/")
server.get("/") do |req, res|
file = File.new("./public/index.html")
content = file.read
res.status = 200
res.body = content
res.set_header("Content-Type", "text/html; charset=utf-8")
end
# GET Index Action
server.get('/items') do |req, res|
res.status = 200
res.body = { result: ListItem.all }.to_json
res.set_header("Content-Type", "application/json; charset=utf-8")
end
# POST Create Action
server.post('/items') do |req, res|
if req.body.empty?
res.status = 400
res.set_header("Content-Type", "application/json; charset=utf-8")
return nil
end
params = JSON.parse req.body
listItem = ListItem.create(params)
if listItem.valid?
res.status = 200
res.body = { title: listItem.title, checked: listItem.checked, id: listItem.id }.to_json
else
res.status = 400
res.body = { error: listItem.error }.to_json
end
res.set_header("Content-Type", "application/json; charset=utf-8")
end
# PUT Update Action
server.put('/items/{id:[0-9]+}') do |req, res|
if req.body.empty?
res.status = 400
res.set_header("Content-Type", "application/json; charset=utf-8")
return nil
end
params = JSON.parse(req.body)
if params.nil? || params[:title].nil?
res.status = 400
elsif params[:title].length > 40
res.status = 400
else
record = ListItem.find(req.params[:id])
if record
record.update_title(params[:title])
res.status = 200
else
res.status = 404
end
end
end
# PUT Check Action
server.put('/items/{id:[0-9]+}/check') do |req, res|
record = ListItem.find(req.params["id"])
if record
record.check
res.status = 200
else
res.status = 404
end
end
# PUT Check Action
server.put('/items/{id:[0-9]+}/uncheck') do |req, res|
record = ListItem.find(req.params["id"])
if record
record.uncheck
res.status = 200
else
res.status = 404
end
end
# DELETE Delete Action
server.delete('/items/{id:[0-9]+}') do |req, res|
record = ListItem.find(req.params["id"])
if record
record.destroy
res.status = 200
else
res.status = 404
end
end
server.start