Class: Committee::ResponseValidator

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(link) ⇒ ResponseValidator

Returns a new instance of ResponseValidator.



3
4
5
6
7
8
9
10
# File 'lib/committee/response_validator.rb', line 3

def initialize(link)
  @link = link

  # 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

Class Method Details

.validate?(status) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/committee/response_validator.rb', line 12

def self.validate?(status)
  status != 204 and @validate_errors || (200...300).include?(status)
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
# File 'lib/committee/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

  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) && !@validator.validate(data)
    errors = JsonSchema::SchemaError.aggregate(@validator.errors).join("\n")
    raise InvalidResponse, "Invalid response.\n\n#{errors}"
  end
end