Class: Graphql::Voyager::Rails::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/voyager/rails/config.rb

Constant Summary collapse

DEFAULT_HEADERS =
{
  'Content-Type' => ->(_) { 'application/json' },
}
CSRF_TOKEN_HEADER =
{
  "X-CSRF-Token" => -> (view_context) { view_context.form_authenticity_token }
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csrf: true, headers: DEFAULT_HEADERS) ⇒ Config

Returns a new instance of Config.



25
26
27
28
# File 'lib/graphql/voyager/rails/config.rb', line 25

def initialize(csrf: true, headers: DEFAULT_HEADERS)
  @headers = headers.dup
  @csrf = csrf
end

Instance Attribute Details

#csrfObject

Returns the value of attribute csrf.



15
16
17
# File 'lib/graphql/voyager/rails/config.rb', line 15

def csrf
  @csrf
end

#headersHash<String => Proc>

Returns Keys are headers to include in GraphQL requests, values are ‘->(view_context) { … }` procs to determin values.

Examples:

Adding a header to the request

config.headers["My-Header"] = -> (view_context) { "My-Value" }

Returns:

  • (Hash<String => Proc>)

    Keys are headers to include in GraphQL requests, values are ‘->(view_context) { … }` procs to determin values



14
15
16
# File 'lib/graphql/voyager/rails/config.rb', line 14

def headers
  @headers
end

Instance Method Details

#resolve_headers(view_context) ⇒ Object

Call defined procs, add CSRF token if specified



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/graphql/voyager/rails/config.rb', line 31

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