Sha256: 5703060a028458c7d9a3b8089ed03c33a71a380623fa832c85beb40547992efd

Contents?: true

Size: 1.94 KB

Versions: 7

Compression:

Stored size: 1.94 KB

Contents

require 'json'
require 'rack'
require 'cypress_on_rails/configuration'
require 'cypress_on_rails/command_executor'

module CypressOnRails
  # Middleware to handle cypress commands and eval
  class Middleware
    def initialize(app, command_executor = CommandExecutor, file = ::File)
      @app = app
      @command_executor = command_executor
      @file = file
    end

    def call(env)
      request = Rack::Request.new(env)
      if request.path.start_with?('/__cypress__/command')
        configuration.tagged_logged { handle_command(request) }
      else
        @app.call(env)
      end
    end

    private

    def configuration
      CypressOnRails.configuration
    end

    def logger
      configuration.logger
    end

    Command = Struct.new(:name, :options, :cypress_folder) do
      # @return [Array<Cypress::Middleware::Command>]
      def self.from_body(body, configuration)
        if body.is_a?(Array)
          command_params = body
        else
          command_params = [body]
        end
        command_params.map do |params|
          new(params.fetch('name'), params['options'], configuration.cypress_folder)
        end
      end

      def file_path
        "#{cypress_folder}/app_commands/#{name}.rb"
      end
    end

    def handle_command(req)
      body = JSON.parse(req.body.read)
      logger.info "handle_command: #{body}"
      commands = Command.from_body(body, configuration)
      missing_command = commands.find {|command| !@file.exists?(command.file_path) }

      if missing_command.nil?
        results = commands.map { |command| @command_executor.load(command.file_path, command.options) }

        begin
          output = results.to_json
        rescue NoMethodError
          output = {"message" => "Cannot convert to json"}.to_json
        end

        [201, {'Content-Type' => 'application/json'}, [output]]
      else
        [404, {}, ["could not find command file: #{missing_command.file_path}"]]
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
cypress-on-rails-1.9.0 lib/cypress_on_rails/middleware.rb
cypress-on-rails-1.8.1 lib/cypress_on_rails/middleware.rb
cypress-on-rails-1.8.0 lib/cypress_on_rails/middleware.rb
cypress-on-rails-1.7.0 lib/cypress_on_rails/middleware.rb
cypress-on-rails-1.6.0 lib/cypress_on_rails/middleware.rb
cypress-on-rails-1.5.1 lib/cypress_on_rails/middleware.rb
cypress-on-rails-1.5.0 lib/cypress_on_rails/middleware.rb