Class: SlsAdf::Util::Adapter

Inherits:
Object
  • Object
show all
Defined in:
lib/sls_adf/util/adapter.rb

Overview

Custom adapter written for github/graphql-client, built to achieve 2 things:

1. Expose HTTP status of response through the #execute method.
2. Automatically GETs token from token endpoint if call is unauthorised.

Adapter can be customised with special logic when calling SLS ADF APIs.

Instance Method Summary collapse

Instance Method Details

#execute(document:, operation_name: nil, variables: {}, context: {}) ⇒ Hash

GraphQL execution adapter used with the graphql-client library. The Adapter must respond to the execute method with the following method signature.

Link: github.com/github/graphql-client/blob/master/guides/remote-queries.md

Parameters:

  • document (GraphQL::Language::Nodes::Document)

    The query itself.

  • operation_name (String) (defaults to: nil)

    The name of the operation

  • variables (Hash) (defaults to: {})

    A hash of the query variables.

  • context (Hash) (defaults to: {})

    Arbitary hash of values that can be accessed

Returns:

  • (Hash)

    Parsed API response. Sample shape: If successful: { ‘data’ => … } If unsuccessful: { ‘errors’ => … }



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/sls_adf/util/adapter.rb', line 27

def execute(document:, operation_name: nil, variables: {}, context: {}) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
  body = {}
  # Convert document into query parameters
  body['query'] = document.to_query_string
  body['operationName'] = operation_name if operation_name
  body['variables'] = variables if variables.any?

  headers = context.merge(authorization_header(token.token))
  response = execute_call(headers: headers, body: body)

  if response.code == 401 # Unauthorized
    new_headers = context.merge(authorization_header(token.refresh_token))
    response = execute_call(headers: new_headers, body: body)
  end

  if response.code.zero?
    { errors: [{ message: 'Unable to establish a connection' }] }
  else
    JSON.parse(response.body).merge(http_status: response.code)
  end
rescue JSON::ParserError
  { errors: [{ message: 'JSON parsing failed' }] }
end