Sha256: 47f709c61a4a404532f7964fc2b2ebe979241bd3417f4e2b2446a012a3e00baf

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true
require 'request_handler/schema_parser'
require 'request_handler/error'
module RequestHandler
  class BodyParser < SchemaParser
    def initialize(request:, schema:, schema_options: {})
      raise MissingArgumentError, "request.body": 'is missing' if request.body.nil?
      super(schema: schema, schema_options: schema_options)
      @request = request
    end

    def run
      validate_schema(flattened_request_body)
    end

    private

    def flattened_request_body
      body = request_body['data']
      body.merge!(body.delete('attributes') { {} })
      relationships = flatten_relationship_resource_linkages(body.delete('relationships') { {} })
      body.merge!(relationships)
      body
    end

    def flatten_relationship_resource_linkages(relationships)
      relationships.each_with_object({}) do |(k, v), memo|
        resource_linkage = v['data']
        next if resource_linkage.nil?
        memo[k] = resource_linkage
      end
    end

    def request_body
      b = request.body
      b.rewind
      b = b.read
      b.empty? ? {} : MultiJson.load(b)
    end

    attr_reader :request
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
request_handler-0.9.1 lib/request_handler/body_parser.rb
request_handler-0.9.0 lib/request_handler/body_parser.rb