Skip to content

Instantly share code, notes, and snippets.

@crosstyan
Last active June 22, 2020 13:29
Show Gist options
  • Save crosstyan/e623b0f6d7ace6afa86ea067626c1eba to your computer and use it in GitHub Desktop.
Save crosstyan/e623b0f6d7ace6afa86ea067626c1eba to your computer and use it in GitHub Desktop.
A example of sinatra with mongodb
require 'mongoid'
require 'sinatra'
require 'json'
#加上:development避免mongoid找不到环境而报错
#预先在"config/mongoid.yml"创建了, 详情见以上链接.
Mongoid.load!(File.join(File.dirname(__FILE__), 'config', 'mongoid.yml'), :development)
#无需声明id字段, mongoid会自动加上
class Post
include Mongoid::Document
field :title, type: String
field :body, type: String
has_many :comments
end
class Comment
include Mongoid::Document
field :name, type: String
field :message, type: String
belongs_to :post
end
def send_err(code,msg) #定义报错函数
halt code, {'code': code ,'message': msg}.to_json
end
before do
content_type :json #设定每一个路由的content_type
end
get '/' do
'{"text":"Hello World"}'
end
get '/posts' do
Post.all.to_json
end
post '/posts' do
send_err 415,"type error" unless request.env['CONTENT_TYPE'] == 'application/json' #halt 即HTTP状态码
payload= JSON.parse(request.body.read) #如果是JSON的话payload这个变量就装着一个hash, 如果不是JSON就是一个string
if payload.is_a?(Hash) #是hash才接着走
if payload.key?("body") and payload.key?("title") #是否存在这两个字段?
post = Post.create!(body: payload['body'], title: payload['title'])
post.to_json #to_json 会将这个Object转换成JSON(如果可以的话, 不行就变成String)发回去
else
halt 400, payload.to_json
end
else #返回400, 请求数据原封不动丢回去
halt 400, payload.to_json
end
end
get '/posts/:post_id' do |post_id|
begin
post = Post.find(post_id)
rescue => err #返回报错信息
send_err(404,err.to_s)
end
post.attributes.merge(
comments: post.comments,
).to_json
end
post '/posts/:post_id/comments' do |post_id|
send_err(415,"type error") unless request.env['CONTENT_TYPE'] == 'application/json'
payload= JSON.parse(request.body.read)
begin
post = Post.find(post_id)
rescue => err
send_err(404,err.to_s)
end
if payload.is_a?(Hash)
if (['name','message']-payload.keys).empty?
comment = post.comments.create!(name:payload['name'],message:payload['message'])
comment.to_json
else
halt 400, payload.to_json
end
else
halt 400, payload.to_json
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment