Sha256: c23c46e2d77b79aed80429a8134151ebea7b9b1741efc25337690a9b3c85b6ad

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

module Fakeit
  module App
    class << self
      def create(spec_file)
        specification = Fakeit::Openapi.load(spec_file)

        proc do |env|
          request = Rack::Request.new(env)
          specification
            .operation(request.request_method.downcase.to_sym, request.path_info)
            &.tap { |operation| validate(operation, request) }
            .then(&method(:rack_response))
        rescue Fakeit::Validation::ValidationError => e
          error_response(e)
        end
      end

      private

      def error_response(err)
        { message: err.message }
          .to_json
          .then { |message| [418, { 'Content-Type' => 'application/json' }, [message]] }
      end

      def rack_response(operation)
        if operation
          [operation.status, operation.headers, [operation.body]]
        else
          [404, {}, ['Not Found']]
        end
      end

      def validate(operation, request)
        operation.validate(
          body: request.body&.read.to_s,
          params: request.params,
          headers: headers(request)
        )
      end

      def headers(request)
        request
          .each_header
          .select { |k, _| k.start_with? 'HTTP_' }
          .map { |k, v| [k.sub(/^HTTP_/, '').split('_').map(&:capitalize).join('-'), v] }
          .to_h
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fakeit-0.1.1 lib/fakeit/app/app.rb