-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.rb
97 lines (71 loc) · 2.1 KB
/
tasks.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
92
93
94
95
96
97
# Implements Tasks spec defined at:
# http://wiki.sproutcore.com/Todos+06-Building+the+Backend
require 'sinatra'
require 'dm-core'
require 'json'
require 'static_assets'
# Define the data model
DataMapper.setup(:default, ENV['DATABASE_URL'] ||
"sqlite3://#{File.join(File.dirname(__FILE__), 'tmp', 'tasks.db')}")
class Task
include DataMapper::Resource
property :id, Serial
property :description, Text, :nullable => false
property :is_done, Boolean
def url
"/tasks/#{self.id}"
end
def to_json(*a)
{
'guid' => self.url,
'description' => self.description,
'isDone' => self.is_done
}.to_json(*a)
end
# keys that MUST be found in the json
REQUIRED = [:description, :is_done]
# ensure json is safe. If invalid json is received returns nil
def self.parse_json(body)
json = JSON.parse(body)
ret = { :description => json['description'], :is_done => json['isDone'] }
return nil if REQUIRED.find { |r| ret[r].nil? }
ret
end
end
DataMapper.auto_upgrade!
# return list of all installed tasks
get '/tasks' do
content_type 'application/json'
{ 'content' => Array(Task.all) }.to_json
end
# create a new task. request body to contain json
post '/tasks' do
opts = Task.parse_json(request.body.read) rescue nil
halt(401, 'Invalid Format') if opts.nil?
task = Task.new(opts)
task.save!
response['Location'] = task.url
response.status = 201
end
# Get an individual task
get "/tasks/:id" do
task = Task.get(params[:id]) rescue nil
halt(404, 'Not Found') if task.nil?
content_type 'application/json'
{ 'content' => task }.to_json
end
# Update an individual task
put "/tasks/:id" do
task = Task.get(params[:id]) rescue nil
halt(404, 'Not Found') if task.nil?
opts = Task.parse_json(request.body.read) rescue nil
halt(401, 'Invalid Format') if opts.nil?
task.update!(opts)
response['Content-Type'] = 'application/json'
{ 'content' => task }.to_json
end
# Delete an invidual task
delete '/tasks/:id' do
task = Task.get(params[:id]) rescue nil
task.destroy unless task.nil?
end