Class: Committee::ResponseValidator

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of ResponseValidator.



5
6
7
8
9
10
11
12
13
# File 'lib/committee/response_validator.rb', line 5

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

  # we should eventually move off of validating against parent schema too
  # ... this is a Herokuism and not in the specification
  schema = link.target_schema || link.parent
  @validator = JsonSchema::Validator.new(schema)
end

Instance Attribute Details

#validate_errorsObject (readonly)

Returns the value of attribute validate_errors.



3
4
5
# File 'lib/committee/response_validator.rb', line 3

def validate_errors
  @validate_errors
end

Class Method Details

.validate?(status, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
18
19
# File 'lib/committee/response_validator.rb', line 15

def self.validate?(status, options = {})
  validate_errors = options[:validate_errors]

  status != 204 and validate_errors || (200...300).include?(status)
end

Instance Method Details

#call(status, headers, data) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/committee/response_validator.rb', line 21

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

  if @link.rel == "instances" && !@link.target_schema
    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 self.class.validate?(status, validate_errors: validate_errors) && !@validator.validate(data)
    errors = JsonSchema::SchemaError.aggregate(@validator.errors).join("\n")
    raise InvalidResponse, "Invalid response.\n\n#{errors}"
  end
end