Module: Controls::Response

Defined in:
lib/controls/response.rb

Overview

A module to encapsulate middleware customization

Class Method Summary collapse

Class Method Details

.parse(response_body, response_status = nil, path = nil) ⇒ Dish::Plate, Object

Returns the parsed JSON response after marshaling through Dish

Parameters:

  • response_body (String)

    the JSON object to parse

  • path (String) (defaults to: nil)

    the requested API endpoint’s path

Returns:

  • (Dish::Plate, Object)

    a marshaled representation of the JSON response



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
42
43
44
45
46
47
48
49
50
51
# File 'lib/controls/response.rb', line 13

def parse(response_body, response_status = nil, path = nil)
  hash_or_array = JSON.parse(response_body)

  if hash_or_array.is_a?(Hash) && hash_or_array.key?('message') && hash_or_array.key?('documentationUrl')
    type = Controls::Error
  elsif hash_or_array.is_a?(Hash) && hash_or_array.key?('message') && hash_or_array.key?('status')
    type = Controls::Error
  end

  type ||=
    case path
    when %r(^(?:/\d.\d)?/coverage/security_controls)
      Controls::SecurityControlCoverage
    when /(configuration|event|guidance|prioritized_guidance|security_control|threat_vector|trend)s?$/
      Controls.const_get(Regexp.last_match[1].split('_').map(&:capitalize).join)
    when %r(^(?:/\d.\d)?\/(assessment|configuration|guidance|security_control|threat|threat_vector)s?)
      Controls.const_get(Regexp.last_match[1].split('_').map(&:capitalize).join)
    when /findings$/
      Controls::SecurityControlFinding
    # [todo] - these asset related endpoints are inconsisteny create a better regex?
    when %r(^(?:/\d.\d)?/assets/search)
      Controls::AssetCollection
    when /((?:applicable|miconfigured|uncovered|undefended)?_?asset)s$/
      Controls::AssetCollection
    when %r(^(?:/\d.\d)?/((?:applicable|miconfigured|uncovered|undefended)?_?asset)s/)
      Controls::Asset
    else
      Dish::Plate
    end

  Dish(hash_or_array, type)
rescue JSON::ParserError
  opts = { message: 'An error occurred', status: response_status }
  opts.delete_if do |_, value|
    value.nil?
  end

  Controls::Error.new(opts)
end