Class: FunApi::Schema
- Inherits:
-
Object
- Object
- FunApi::Schema
- Defined in:
- lib/funapi/schema.rb
Class Method Summary collapse
- .define(&block) ⇒ Object
- .validate(schema, data, location: "body") ⇒ Object
- .validate_response(schema, data) ⇒ Object
Class Method Details
.define(&block) ⇒ Object
5 6 7 |
# File 'lib/funapi/schema.rb', line 5 def self.define(&block) Dry::Schema.Params(&block) end |
.validate(schema, data, location: "body") ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/funapi/schema.rb', line 9 def self.validate(schema, data, location: "body") return data unless schema if schema.is_a?(Array) && schema.length == 1 item_schema = schema.first data_array = data.is_a?(Array) ? data : [] results = data_array.map do |item| result = item_schema.call(item || {}) raise ValidationError.new(errors: result.errors) unless result.success? result.to_h end return results end result = schema.call(data || {}) raise ValidationError.new(errors: result.errors) unless result.success? result.to_h end |
.validate_response(schema, data) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/funapi/schema.rb', line 32 def self.validate_response(schema, data) return data unless schema if schema.is_a?(Array) && schema.length == 1 item_schema = schema.first data_array = data.is_a?(Array) ? data : [] return data_array.map do |item| result = item_schema.call(item) unless result.success? raise HTTPException.new( status_code: 500, detail: "Response validation failed: #{result.errors.to_h}" ) end result.to_h end end result = schema.call(data) unless result.success? raise HTTPException.new( status_code: 500, detail: "Response validation failed: #{result.errors.to_h}" ) end result.to_h end |