Handle invalid JSON on PUT requests

This commit is contained in:
galfert 2012-10-06 18:44:21 +02:00
parent 84e69376fd
commit acf2003487
2 changed files with 45 additions and 5 deletions

View File

@ -63,12 +63,11 @@ module RemoteStorage
def put_data(user, directory, key, data, content_type=nil) def put_data(user, directory, key, data, content_type=nil)
object = data_bucket.new("#{user}:#{directory}:#{key}") object = data_bucket.new("#{user}:#{directory}:#{key}")
object.content_type = content_type || "text/plain; charset=utf-8" object.content_type = content_type || "text/plain; charset=utf-8"
data = JSON.parse(data) if content_type[/^[^;\s]+/] == "application/json"
if serializer_for(object.content_type) unless set_object_data(object, data)
object.data = data halt 422
else
object.raw_data = data
end end
directory_index = directory == "" ? "/" : directory directory_index = directory == "" ? "/" : directory
object.indexes.merge!({:user_id_bin => [user], object.indexes.merge!({:user_id_bin => [user],
:directory_bin => [directory_index]}) :directory_bin => [directory_index]})
@ -206,5 +205,20 @@ module RemoteStorage
directory_object.store directory_object.store
end end
def set_object_data(object, data)
if object.content_type[/^[^;\s]+/] == "application/json"
data = "{}" if data.blank?
data = JSON.parse(data)
end
if serializer_for(object.content_type)
object.data = data
else
object.raw_data = data
end
rescue JSON::ParserError
return false
end
end end
end end

View File

@ -173,6 +173,32 @@ describe "App with Riak backend" do
last_response.content_type.must_equal "application/json; charset=UTF-8" last_response.content_type.must_equal "application/json; charset=UTF-8"
end end
end end
context "invalid JSON" do
context "empty body" do
before do
header "Content-Type", "application/json"
put "/jimmy/documents/jason", ""
end
it "saves an empty JSON object" do
last_response.status.must_equal 200
data_bucket.get("jimmy:documents:jason").data.must_be_kind_of Hash
data_bucket.get("jimmy:documents:jason").data.must_equal({})
end
end
context "unparsable JSON" do
before do
header "Content-Type", "application/json"
put "/jimmy/documents/jason", "foo"
end
it "returns a 422" do
last_response.status.must_equal 422
end
end
end
end end
describe "DELETE" do describe "DELETE" do