Class: Steppe::Endpoint::PayloadValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/steppe/endpoint.rb

Overview

Internal step that validates request payload against a schema for a specific content type. Only validates if the request content type matches. Or if the request is form or multipart, which Rack::Request parses by default. Merges validated payload into result params. Returns 422 Unprocessable Entity if validation fails.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content_type, payload_schema) ⇒ PayloadValidator

Returns a new instance of PayloadValidator.

Parameters:

  • content_type (String)

    Content type to validate (e.g., ‘application/json’)



155
156
157
158
# File 'lib/steppe/endpoint.rb', line 155

def initialize(content_type, payload_schema)
  @content_type = content_type
  @payload_schema = payload_schema.is_a?(Hash) ? Types::Hash[payload_schema] : payload_schema
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



152
153
154
# File 'lib/steppe/endpoint.rb', line 152

def content_type
  @content_type
end

#payload_schemaObject (readonly)

Returns the value of attribute payload_schema.



152
153
154
# File 'lib/steppe/endpoint.rb', line 152

def payload_schema
  @payload_schema
end

Instance Method Details

#call(conn) ⇒ Result

Returns Updated result with validated params or error response.

Parameters:

  • conn (Result)

    The current result/connection object

Returns:

  • (Result)

    Updated result with validated params or error response



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/steppe/endpoint.rb', line 162

def call(conn)
  # If form or multipart, treat as form data
  data = nil
  if conn.request.form_data?
    data = Utils.deep_symbolize_keys(conn.request.POST)
  elsif content_type.media_type == conn.request.media_type
    # request.body was already parsed by parser associated to this media type
    data = conn.request.body
  else
    return conn
  end

  result = payload_schema.resolve(data)
  conn = conn.copy(params: conn.params.merge(result.value))
  return conn if result.valid?

  conn.respond_with(422).invalid(errors: result.errors)
end