File: accept_version_header.rb

package info (click to toggle)
ruby-grape 1.6.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,156 kB
  • sloc: ruby: 25,265; makefile: 7
file content (65 lines) | stat: -rw-r--r-- 2,113 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true

require 'grape/middleware/base'

module Grape
  module Middleware
    module Versioner
      # This middleware sets various version related rack environment variables
      # based on the HTTP Accept-Version header
      #
      # Example: For request header
      #    Accept-Version: v1
      #
      # The following rack env variables are set:
      #
      #    env['api.version']  => 'v1'
      #
      # If version does not match this route, then a 406 is raised with
      # X-Cascade header to alert Grape::Router to attempt the next matched
      # route.
      class AcceptVersionHeader < Base
        def before
          potential_version = (env[Grape::Http::Headers::HTTP_ACCEPT_VERSION] || '').strip

          if strict? && potential_version.empty?
            # If no Accept-Version header:
            throw :error, status: 406, headers: error_headers, message: 'Accept-Version header must be set.'
          end

          return if potential_version.empty?

          # If the requested version is not supported:
          throw :error, status: 406, headers: error_headers, message: 'The requested version is not supported.' unless versions.any? { |v| v.to_s == potential_version }

          env[Grape::Env::API_VERSION] = potential_version
        end

        private

        def versions
          options[:versions] || []
        end

        def strict?
          options[:version_options] && options[:version_options][:strict]
        end

        # By default those errors contain an `X-Cascade` header set to `pass`, which allows nesting and stacking
        # of routes (see Grape::Router) for more information). To prevent
        # this behavior, and not add the `X-Cascade` header, one can set the `:cascade` option to `false`.
        def cascade?
          if options[:version_options]&.key?(:cascade)
            options[:version_options][:cascade]
          else
            true
          end
        end

        def error_headers
          cascade? ? { Grape::Http::Headers::X_CASCADE => 'pass' } : {}
        end
      end
    end
  end
end