Support x-nullable in respone_validator

This commit is contained in:
richie 2016-10-17 14:47:11 -07:00
parent 5a19cd2373
commit 5df130922f
2 changed files with 34 additions and 3 deletions

View File

@ -0,0 +1,25 @@
require 'json-schema'
module Rswag
module Specs
class ExtendedSchema < JSON::Schema::Validator
def initialize
super
extend_schema_definition("http://json-schema.org/draft-04/schema#")
@attributes['type'] = ExtendedTypeAttribute
@uri = URI.parse('http://tempuri.org/rswag/specs/extended_schema')
end
end
class ExtendedTypeAttribute < JSON::Schema::TypeV4Attribute
def self.validate(current_schema, data, fragments, processor, validator, options={})
return if data.nil? && current_schema.schema['x-nullable'] == true
super
end
end
JSON::Validator.register_validator(ExtendedSchema.new)
end
end

View File

@ -1,4 +1,6 @@
require 'active_support/core_ext/hash/slice'
require 'json-schema'
require 'rswag/specs/extended_schema'
module Rswag
module Specs
@ -23,10 +25,14 @@ module Rswag
end
def validate_body!(body)
schema = @api_metadata[:response][:schema]
return if schema.nil?
response_schema = @api_metadata[:response][:schema]
return if response_schema.nil?
begin
JSON::Validator.validate!(schema.merge(@global_metadata), body)
validation_schema = response_schema
.merge('$schema' => 'http://tempuri.org/rswag/specs/extended_schema')
.merge(@global_metadata.slice(:definitions))
JSON::Validator.validate!(validation_schema, body)
rescue JSON::Schema::ValidationError => ex
raise UnexpectedResponse, "Expected response body to match schema: #{ex.message}"
end