-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbird_service.rb
More file actions
42 lines (35 loc) · 1.06 KB
/
bird_service.rb
File metadata and controls
42 lines (35 loc) · 1.06 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
require 'sinatra/base'
require 'mongoid'
require_relative './models/bird'
class BirdService < Sinatra::Base
configure do
Mongoid.load!("config/mongoid.yml")
end
before do
content_type :json
halt 415, "invalid mime type" unless request.content_type == 'application/json'
end
get '/birds' do
birds = Bird.all.where(:visible => true)
birds.to_json
end
post '/birds' do
request_payload = JSON.parse (request.body.read) rescue {}
bird = Bird.new(request_payload)
halt 400, bird.errors.as_json(full_messages: true).to_json unless bird.valid?
bird.save
bird.to_json
end
get '/birds/:id' do
halt 404, {:message=>"Not found"}.to_json unless BSON::ObjectId.legal?(params[:id])
bird = Bird.find(params[:id])
halt 404, {:message=>"Not found"}.to_json if bird.nil?
bird.to_json
end
delete '/birds/:id' do
halt 404, {:message=>"Not found"}.to_json unless BSON::ObjectId.legal?(params[:id])
bird = Bird.find(params[:id])
halt 404, {:message=>"Not found"}.to_json if bird.nil?
bird.destroy
end
end