require 'json'
require 'yaml'

module Rswag
  module Api
    class Middleware 

      def initialize(app, config)
        @app = app
        @config = config
      end

      def call(env)
        path = env['PATH_INFO']
        filename = "#{@config.resolve_swagger_root(env)}/#{path}"

        if env['REQUEST_METHOD'] == 'GET' && File.file?(filename)
          swagger = parse_file(filename)
          @config.swagger_filter.call(swagger, env) unless @config.swagger_filter.nil?

          return [
            '200',
            { 'Content-Type' => 'application/json' },
            [ JSON.dump(swagger) ]
          ]
        end
          
        return @app.call(env)
      end

      private

      def parse_file(filename)
        if /\.yml$/ === filename
          load_yaml(filename)
        else
          load_json(filename)
        end
      end

      def load_yaml(filename)
        YAML.safe_load(File.read(filename))
      end

      def load_json(filename)
        JSON.parse(File.read(filename))
      end
    end
  end
end

require 'json'
require 'yaml'

module Rswag
  module Api
    class Middleware 

      def initialize(app, config)
        @app = app
        @config = config
      end

      def call(env)
        path = env['PATH_INFO']
        filename = "#{@config.resolve_swagger_root(env)}/#{path}"

        if env['REQUEST_METHOD'] == 'GET' && File.file?(filename)
          swagger = parse_file(filename)
          @config.swagger_filter.call(swagger, env) unless @config.swagger_filter.nil?

          return [
            '200',
            { 'Content-Type' => 'application/json' },
            [ JSON.dump(swagger) ]
          ]
        end
          
        return @app.call(env)
      end

      private

      def parse_file(filename)
        if /\.ya?ml$/ === filename
          load_yaml(filename)
        else
          load_json(filename)
        end
      end

      def load_yaml(filename)
        YAML.safe_load(File.read(filename))
      end

      def load_json(filename)
        JSON.parse(File.read(filename))
      end
    end
  end
end

Allow ".yaml" and ".yml" filename endings for yaml
Allow ".yaml" and ".yml" filename endings for yaml
