Class: Mj::GraphQL::RequestFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/mj/graphql/request_factory.rb

Instance Method Summary collapse

Instance Method Details

#from_file(file) ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize, Metrics/MethodLength



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
# File 'lib/mj/graphql/request_factory.rb', line 8

def from_file(file) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize, Metrics/MethodLength
  contents = File.read(file)
  comments = contents.split("\n").take_while { |line| line.match(/^#/) }.join("\n")
  query = contents.split("\n").drop_while { |line| line.match(/^#/) }.join("\n")
  endpoint = comments.match(/# gql-endpoint: (.+)/)&.captures&.first

  request = Request.new(query: query, endpoint: endpoint)

  headers = comments.split("\n")
    .select { |line| line.match(/^# gql-header:/) }
    .map { |line| line.split("gql-header:")[1..].join.strip }

  headers.map do |value|
    values = value.split(":").map(&:strip)
    request = request.with_header(*values)
  end

  variables_string = comments.match(/# gql-variables:\s?(.+)/)&.captures&.first

  if variables_string
    variables = JSON.parse(variables_string)
    request = request.with_variables(variables)
  end

  request
end