Sha256: a00168bb23e51edbe64a3ecde65e8d3f69cd1a977905cadf42cbef90806f23d3

Contents?: true

Size: 1.03 KB

Versions: 23

Compression:

Stored size: 1.03 KB

Contents

require 'json'
require 'hashie'

module Routemaster
  module Middleware
    # Receives a JSON payload of Routemaster events and parses it.
    #
    # It also ignores anything but POST with `application/json` MIMEs.
    #
    # Lower middlewares (or the app) can access the parsed payload as a hash
    # in +env['routemaster.payload']+
    class Parse
      def initialize(app)
        @app  = app
      end

      def call(env)
        if (env['CONTENT_TYPE'] != 'application/json')
          return [415, {}, []]
        end
        if (payload = _extract_payload(env))
          env['routemaster.payload'] = payload
        else
          return [400, {}, []]
        end
        @app.call(env)
      end

      private

      def _extract_payload(env)
        data = JSON.parse(env['rack.input'].read).map { |e| Hashie::Mash.new(e) }
        return nil unless data.kind_of?(Array)
        return nil unless data.all? { |e| e.t && e.type && e.topic && e.url }
        return data
      rescue JSON::ParserError
        nil
      end
    end
  end
end


Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
routemaster-drain-3.6.2 lib/routemaster/middleware/parse.rb
routemaster-drain-3.6.1 lib/routemaster/middleware/parse.rb
routemaster-drain-3.6.0 lib/routemaster/middleware/parse.rb
routemaster-drain-3.5.1 lib/routemaster/middleware/parse.rb
routemaster-drain-3.5.0 lib/routemaster/middleware/parse.rb
routemaster-drain-3.4.0 lib/routemaster/middleware/parse.rb
routemaster-drain-3.3.0 lib/routemaster/middleware/parse.rb
routemaster-drain-3.2.0 lib/routemaster/middleware/parse.rb
routemaster-drain-3.1.0 lib/routemaster/middleware/parse.rb
routemaster-drain-3.0.3 lib/routemaster/middleware/parse.rb
routemaster-drain-3.0.2 lib/routemaster/middleware/parse.rb
routemaster-drain-3.0.1 lib/routemaster/middleware/parse.rb
routemaster-drain-3.0.0 lib/routemaster/middleware/parse.rb
routemaster-drain-2.5.4 lib/routemaster/middleware/parse.rb
routemaster-drain-2.5.3 lib/routemaster/middleware/parse.rb
routemaster-drain-2.5.2 lib/routemaster/middleware/parse.rb
routemaster-drain-2.5.1 lib/routemaster/middleware/parse.rb
routemaster-drain-2.5.0 lib/routemaster/middleware/parse.rb
routemaster-drain-2.4.4 lib/routemaster/middleware/parse.rb
routemaster-drain-2.4.3 lib/routemaster/middleware/parse.rb