Skip to content

Commit c23f5d9

Browse files
author
Marcin Olichwirowicz
committed
More strict behaviour in versioner
1 parent fca7d6d commit c23f5d9

File tree

2 files changed

+45
-9
lines changed

2 files changed

+45
-9
lines changed

lib/grape/middleware/versioner/header.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def before
2626
accept = env['HTTP_ACCEPT'] || ""
2727

2828
if options[:version_options] && options[:version_options].keys.include?(:strict) && options[:version_options][:strict]
29-
if (accept.nil? || accept.empty?) && options[:versions] && options[:version_options][:using] == :header
29+
if (incorrect_header?(accept)) && options[:versions] && options[:version_options][:using] == :header
3030
throw :error, :status => 404, :headers => {'X-Cascade' => 'pass'}, :message => "404 API Version Not Found"
3131
end
3232
end
@@ -48,6 +48,11 @@ def before
4848
end
4949
end
5050
end
51+
52+
protected
53+
def incorrect_header?(header)
54+
(header.strip =~ /application\/vnd\.(.+?)-(.+?)\+(.+?)/).nil?
55+
end
5156
end
5257
end
5358
end

spec/grape/middleware/versioner/header_spec.rb

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -69,15 +69,46 @@
6969
subject.call({}).first.should == 200
7070
end
7171

72-
it 'should return a 404 when no header is set but strict header based versioning is used' do
73-
@options = {
74-
:versions => ['v1'],
75-
:version_options => {:using => :header, :strict => true}
76-
}
77-
expect {
78-
env = subject.call('HTTP_ACCEPT' => '').last
79-
}.to throw_symbol(:error, :status => 404, :headers => {'X-Cascade' => 'pass'}, :message => "404 API Version Not Found")
72+
context 'when strict header versioning is used' do
73+
it 'should return a 404 when no header' do
74+
@options = {
75+
:versions => ['v1'],
76+
:version_options => {:using => :header, :strict => true}
77+
}
78+
expect {
79+
env = subject.call('HTTP_ACCEPT' => '').last
80+
}.to throw_symbol(
81+
:error,
82+
:status => 404,
83+
:headers => {'X-Cascade' => 'pass'},
84+
:message => "404 API Version Not Found"
85+
)
86+
end
87+
88+
it 'should return a 404 when incorrect header format is used' do
89+
@options = {
90+
:versions => ['v1'],
91+
:version_options => {:using => :header, :strict => true}
92+
}
93+
expect {
94+
env = subject.call('HTTP_ACCEPT' => '*/*').last
95+
}.to throw_symbol(
96+
:error,
97+
:status => 404,
98+
:headers => {'X-Cascade' => 'pass'},
99+
:message => "404 API Version Not Found"
100+
)
101+
end
102+
103+
it 'should return a 200 when proper header is set' do
104+
@options = {
105+
:versions => ['v1'],
106+
:version_options => {:using => :header, :strict => true}
107+
}
108+
subject.call('HTTP_ACCEPT' => 'application/vnd.testing-v1+json').first.should == 200
109+
end
80110
end
111+
81112
end
82113

83114
context 'vendors' do

0 commit comments

Comments
 (0)