Class: Committee::ResponseValidator

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

Instance Method Summary collapse

Methods included from Validation

#check_format, #check_format!, #check_pattern, #check_pattern!, #check_type, #check_type!

Constructor Details

#initialize(data, schema, link_schema, type_schema) ⇒ ResponseValidator

Returns a new instance of ResponseValidator.



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

def initialize(data, schema, link_schema, type_schema)

  @data = data
  @schema = schema
  @link_schema = link_schema
  @type_schema = type_schema
end

Instance Method Details

#callObject



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

def call
  data = if @link_schema["rel"] == "instances"
    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
    @data[0]
  else
    @data
  end

  data_keys = build_data_keys(data)
  schema_keys = build_schema_keys

  extra = data_keys - schema_keys
  missing = schema_keys - data_keys

  errors = []

  if extra.count > 0
    errors << "Extra keys in response: #{extra.join(', ')}."
  end

  if missing.count > 0
    errors << "Missing keys in response: #{missing.join(', ')}."
  end

  unless errors.empty?
    raise InvalidResponse, ["`#{@link_schema['method']} #{@link_schema['href']}` deviates from schema.", *errors].join(' ')
  end

  check_data!(@type_schema, data, [])
end

#check_data!(schema, data, path) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/committee/response_validator.rb', line 47

def check_data!(schema, data, path)
  schema["properties"].each do |key, value|
    if value["properties"]
      check_data!(value, data[key], path + [key])
    elsif value["type"] == ["array"]
      definition = @schema.find(value["items"]["$ref"])
      data[key].each do |datum|
        check_type!(definition["type"], datum, path + [key])
        unless definition["type"].include?("null") && datum.nil?
          check_format!(definition["format"], datum, path + [key])
          check_pattern!(definition["pattern"], datum, path + [key])
        end
      end

    else
      definition = @schema.find(value["$ref"])
      check_type!(definition["type"], data[key], path + [key])
      unless definition["type"].include?("null") && data[key].nil?
        check_format!(definition["format"], data[key], path + [key])
        check_pattern!(definition["pattern"], data[key], path + [key])
      end
    end
  end
end