Skip to content

Commit

Permalink
detect if we're encoding or not by methods but payload
Browse files Browse the repository at this point in the history
because we might really want to post/put a false or nil!
  • Loading branch information
godfat committed Nov 15, 2014
1 parent f4d845b commit ba8941a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
5 changes: 3 additions & 2 deletions lib/rest-core/middleware/json_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ def self.members; [:json_request]; end
include RestCore::Middleware

JSON_REQUEST_HEADER = {'Content-Type' => 'application/json'}.freeze
JSON_REQUEST_METHOD = [:post, :put, :patch]

def call env, &k
return app.call(env, &k) unless json_request(env)
return app.call(env, &k) unless env[REQUEST_PAYLOAD] &&
!env[REQUEST_PAYLOAD].empty?
return app.call(env, &k) unless
JSON_REQUEST_METHOD.include?(env[REQUEST_METHOD])

app.call(env.merge(
REQUEST_HEADERS => JSON_REQUEST_HEADER.merge(env[REQUEST_HEADERS]||{}),
Expand Down
2 changes: 1 addition & 1 deletion task
Submodule task updated 1 files
+15 −5 gemgem.rb
20 changes: 16 additions & 4 deletions test/test_json_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

describe RC::JsonRequest do
app = RC::JsonRequest.new(RC::Dry.new, true)
env = {RC::REQUEST_HEADERS => {}}
env = {RC::REQUEST_HEADERS => {}, RC::REQUEST_METHOD => :post}
request_params = {
'key' => 'value',
'array' => [1, 2, 3],
Expand All @@ -21,9 +21,21 @@
RC::REQUEST_PAYLOAD => RC::Json.encode(request_params))}
end

would 'do nothing if payload is empty' do
e = env.merge(RC::REQUEST_PAYLOAD => {})
app.call(e){ |res| res.should.eq e }
would 'encode false and nil' do
[[nil, 'null'], [false, 'false'], [true, 'true']].each do |(value, exp)|
[:post, :put, :patch].each do |meth|
e = env.merge(RC::REQUEST_METHOD => meth,
RC::REQUEST_PAYLOAD => value)
app.call(e){ |res| res[RC::REQUEST_PAYLOAD].should.eq(exp) }
end
end
end

would 'do nothing for get, delete, head, options' do
[:get, :delete, :head, :options].each do |meth|
e = env.merge(RC::REQUEST_PAYLOAD => {}, RC::REQUEST_METHOD => meth)
app.call(e){ |res| res.should.eq e }
end
end

would 'do nothing if json_request is false' do
Expand Down

0 comments on commit ba8941a

Please sign in to comment.