Skip to content

Commit

Permalink
Merge pull request #16 from collectiveidea/dg/fix-rack-3
Browse files Browse the repository at this point in the history
Fix conditional post
  • Loading branch information
albus522 committed May 20, 2024
2 parents 1749455 + 7687d0d commit 32097c4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/twirp/rails/rack/conditional_post.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ def call(env)
when "POST"
status, headers, body = response = @app.call(env)
# Rack 3 settles on only allowing lowercase headers
if Rack.release < "3.0"
if ::Rack.release < "3.0"
headers = ::Rack::Utils::HeaderHash[headers]
end

if status == 200 && fresh?(env, headers)
response[0] = 304
headers.delete(::Rack::CONTENT_TYPE)
headers.delete(::Rack::CONTENT_LENGTH)
response[2] = Rack::BodyProxy.new([]) do
response[2] = ::Rack::BodyProxy.new([]) do
body.close if body.respond_to?(:close)
end
end
Expand Down
4 changes: 3 additions & 1 deletion spec/rails_app/config/initializers/twirp_rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@
end

Rails.application.config.twirp.middleware = [
Rack::Deflater
Rack::Deflater,
Twirp::Rails::Rack::ConditionalPost,
Rack::ETag
]
25 changes: 25 additions & 0 deletions spec/requests/haberdasher_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,29 @@ def make_hat_success_request
expect(response.headers["Content-Encoding"]).to be_nil
end
end

describe "caching" do
it "respects cache headers to return 304 statuses" do
size = Twirp::Example::Haberdasher::Size.new(inches: 24)

post "/twirp/twirp.example.haberdasher.Haberdasher/MakeHat",
params: size.to_proto, headers: {
:accept => "application/protobuf",
"Content-Type" => "application/protobuf"
}
expect(response).to be_successful
decoded = Twirp::Example::Haberdasher::Hat.decode(response.body)
expect(decoded).to be_a(Twirp::Example::Haberdasher::Hat)
expect(response.etag).to be_present

post "/twirp/twirp.example.haberdasher.Haberdasher/MakeHat",
params: size.to_proto, headers: {
:accept => "application/protobuf",
"Content-Type" => "application/protobuf",
"If-None-Match" => response.etag
}

expect(response.status).to eq(304)
end
end
end

0 comments on commit 32097c4

Please sign in to comment.