Last active
October 29, 2017 14:42
-
-
Save max-power/9338766 to your computer and use it in GitHub Desktop.
Sinatra + MongoDB + JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "sinatra" | |
require "mongo" | |
require "json" | |
class SimpleMongoApi < Sinatra::Base | |
set :mongo, Mongo::Client.new("mongodb://my.mongo.host/database") | |
def collection | |
settings.mongo["things"] | |
end | |
def object | |
collection.find(id_selector(params[:id])) | |
end | |
def id_selector(id) | |
{ _id: BSON::ObjectId.legal?(id) ? BSON::ObjectId.from_string(id.to_s) : id } | |
end | |
before do | |
content_type :json | |
end | |
get '/' do | |
collection.find.limit(params.fetch(:limit, 20).to_i) | |
end | |
post '/' do | |
collection.insert_one params[:thing] | |
end | |
get '/:id' do | |
object.first | |
end | |
put '/:id' do | |
object.find_one_and_replace(params[:thing], return_document: :after) | |
end | |
delete '/:id' do | |
object.find_one_and_delete | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment