Class: Committee::SchemaValidator::HyperSchema::ResponseValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/committee/schema_validator/hyper_schema/response_validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(link, options = {}) ⇒ ResponseValidator

Returns a new instance of ResponseValidator.



9
10
11
12
13
14
# File 'lib/committee/schema_validator/hyper_schema/response_validator.rb', line 9

def initialize(link, options = {})
  @link = link
  @validate_success_only = options[:validate_success_only]

  @validator = JsonSchema::Validator.new(target_schema(link))
end

Instance Attribute Details

#validate_success_onlyObject (readonly)

Returns the value of attribute validate_success_only.



7
8
9
# File 'lib/committee/schema_validator/hyper_schema/response_validator.rb', line 7

def validate_success_only
  @validate_success_only
end

Instance Method Details

#call(status, headers, data) ⇒ Object



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
# File 'lib/committee/schema_validator/hyper_schema/response_validator.rb', line 16

def call(status, headers, data)
  unless status == 204 # 204 No Content
    response = Rack::Response.new(data, status, headers)
    check_content_type!(response)
  end

  # List is a special case; expect data in an array.
  #
  # This is poor form that's here so as not to introduce breaking behavior.
  # The "instances" value of "rel" is a Heroku-ism and was originally
  # introduced before we understood how to use "targetSchema". It's not
  # meaningful with the context of the hyper-schema specification and
  # should be eventually be removed.
  if legacy_hyper_schema_rel?(@link)
    if !data.is_a?(Array)
      raise InvalidResponse, "List endpoints must return an array of objects."
    end

    # only consider the first object during the validation from here on
    # (but only in cases where `targetSchema` is not set)
    data = data[0]

    # if the array was empty, allow it through
    return if data == nil
  end

  if Committee::Middleware::ResponseValidation.validate?(status, validate_success_only) && !@validator.validate(data)
    errors = JsonSchema::SchemaError.aggregate(@validator.errors).join("\n")
    raise InvalidResponse, "Invalid response.\n\n#{errors}"
  end
end