Skip to content

Commit c19c21b

Browse files
twsschingor13
authored andcommitted
Allow custom ‘Accept’ header, prepends ‘application/vnd.api+json’ if it is missing. (#245)
1 parent 5b554b1 commit c19c21b

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

lib/json_api_client/middleware/json_request.rb

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,25 @@ module JsonApiClient
22
module Middleware
33
class JsonRequest < Faraday::Middleware
44
def call(environment)
5+
accept_header = update_accept_header(environment[:request_headers])
6+
57
environment[:request_headers]["Content-Type"] = 'application/vnd.api+json'
6-
environment[:request_headers]["Accept"] = 'application/vnd.api+json'
8+
environment[:request_headers]["Accept"] = accept_header
79
@app.call(environment)
810
end
11+
12+
private
13+
14+
def update_accept_header(headers)
15+
return 'application/vnd.api+json' if headers["Accept"].nil?
16+
accept_params = headers["Accept"].split(",")
17+
18+
unless accept_params.include?('application/vnd.api+json')
19+
accept_params.unshift('application/vnd.api+json')
20+
end
21+
22+
accept_params.join(",")
23+
end
924
end
1025
end
1126
end

test/unit/custom_header_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,24 @@ def test_can_set_custom_headers
2323
end
2424
end
2525

26+
def test_can_set_custom_accept_headers
27+
stub_request(:get, "http://example.com/custom_header_resources/1")
28+
.with(headers: {"Accept" => "application/vnd.api+json,application/vnd.api+json;version=2"})
29+
.to_return(headers: {accept: "application/vnd.api+json,application/vnd.api+json;version=2", content_type: "application/vnd.api+json"}, body: {
30+
data: {
31+
type: "custom_header_resources",
32+
id: "1",
33+
attributes: {
34+
title: "My Blooming Test!"
35+
}
36+
}
37+
}.to_json)
38+
39+
CustomHeaderResource.with_headers(accept: "application/vnd.api+json,application/vnd.api+json;version=2") do
40+
CustomHeaderResource.find(1)
41+
end
42+
end
43+
2644
def test_class_method_headers
2745
stub_request(:post, "http://example.com/custom_header_resources")
2846
.with(headers: {"X-My-Header" => "asdf"})

0 commit comments

Comments
 (0)