Sha256: d717327566b73f909a4cb46c75dbbdcf425196260b2ac3cd1b0dcfdc2f714fd9

Contents?: true

Size: 1.46 KB

Versions: 2

Compression:

Stored size: 1.46 KB

Contents

module Fakeit
  module App
    class << self
      def create(spec_file, options)
        specification = Fakeit::Openapi::Specification.new(spec_file)

        proc do |env|
          request = Rack::Request.new(env)
          specification
            .operation(request.request_method.downcase.to_sym, request.path_info, options)
            .then { |operation| operation ? handle(operation, request, options) : not_found }
        end
      end

      private

      def handle(operation, request, options)
        validate(operation, request)
        response(operation)
      rescue Fakeit::Validation::ValidationError => e
        Fakeit::Logger.warn(Rainbow(e.message).red)
        options.permissive ? response(operation) : error(e)
      end

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

      def not_found
        [404, {}, ['Not Found']]
      end

      def response(operation)
        [operation.status, operation.headers, [operation.body]]
      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

2 entries across 2 versions & 1 rubygems

Version Path
fakeit-0.4.1 lib/fakeit/app/app.rb
fakeit-0.4.0 lib/fakeit/app/app.rb