Class: NulogyGraphqlApi::GraphqlResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/nulogy_graphql_api/graphql_response.rb

Overview

This class provides a wrapper around the hash returned by GraphQL::Schema#execute.

The hash is assumed to have String keys rather than Symbol keys because that is what the Graphql-ruby gem outputs.

Instance Method Summary collapse

Constructor Details

#initialize(graphql_response_json) ⇒ GraphqlResponse

Returns a new instance of GraphqlResponse.



7
8
9
# File 'lib/nulogy_graphql_api/graphql_response.rb', line 7

def initialize(graphql_response_json)
  @graphql_response_json = graphql_response_json
end

Instance Method Details

#contains_errors?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/nulogy_graphql_api/graphql_response.rb', line 41

def contains_errors?
  contains_errors_in_graphql_errors? || contains_errors_in_data_payload?
end

#contains_errors_in_data_payload?Boolean

Detects errors embedded in the GraphQL schema (intended to be shown to end-users): {

"data": {
  "somePayload": {
    "errors": [{
      "message": "Something went wrong!"
    }]
  }
}

}

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
29
# File 'lib/nulogy_graphql_api/graphql_response.rb', line 21

def contains_errors_in_data_payload?
  if @graphql_response_json["data"].present?
    @graphql_response_json["data"].values.any? do |payload|
      payload.is_a?(Hash) ? payload["errors"].present? : false
    end
  else
    false
  end
end

#contains_errors_in_graphql_errors?Boolean

Detects errors in the standard GraphQL error list (intended to be shown to developers and API clients): {

"errors": [{
  "message": "Something went wrong!"
}]

}

Returns:

  • (Boolean)


37
38
39
# File 'lib/nulogy_graphql_api/graphql_response.rb', line 37

def contains_errors_in_graphql_errors?
  @graphql_response_json["errors"].present?
end

#http_response_codeObject



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/nulogy_graphql_api/graphql_response.rb', line 45

def http_response_code
  if contains_errors_in_graphql_errors?
    400
  elsif contains_errors_in_data_payload?
    # mimic Rails behaviour when there are validation errors. Also enable clients to easily
    # identify user-facing errors. CPI for instance will retry these to deal with race
    # conditions.
    422
  else
    200
  end
end

#render_http_responseObject



58
59
60
61
62
63
# File 'lib/nulogy_graphql_api/graphql_response.rb', line 58

def render_http_response
  {
    json: @graphql_response_json,
    status: http_response_code
  }
end