File: config.rb

package info (click to toggle)
ruby-graphiql-rails 1.4.10-1
  • links: PTS, VCS
  • area: contrib
  • in suites: bookworm, bullseye, buster
  • size: 6,640 kB
  • sloc: ruby: 226; makefile: 4
file content (41 lines) | stat: -rw-r--r-- 1,261 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
module GraphiQL
  module Rails
    class Config
      # @example Adding a header to the request
      #    config.headers["My-Header"] = -> (view_context) { "My-Value" }
      #
      # @return [Hash<String => Proc>] Keys are headers to include in GraphQL requests, values are `->(view_context) { ... }` procs to determin values
      attr_accessor :headers

      attr_accessor :query_params, :initial_query, :csrf

      DEFAULT_HEADERS = {
        'Content-Type' => ->(_) { 'application/json' },
      }

      CSRF_TOKEN_HEADER = {
        "X-CSRF-Token" => -> (view_context) { view_context.form_authenticity_token }
      }

      def initialize(query_params: false, initial_query: nil, csrf: true, headers: DEFAULT_HEADERS)
        @query_params = query_params
        @headers = headers.dup
        @initial_query = initial_query
        @csrf = csrf
      end

      # Call defined procs, add CSRF token if specified
      def resolve_headers(view_context)
        all_headers = DEFAULT_HEADERS.merge(headers)

        if csrf
          all_headers = all_headers.merge(CSRF_TOKEN_HEADER)
        end

        all_headers.each_with_object({}) do |(key, value), memo|
          memo[key] = value.call(view_context)
        end
      end
    end
  end
end