Sha256: 9cdaaaf788440fa4d9b605f308fa83acc6c985c3035733bd2f6cfc12f585ff01

Contents?: true

Size: 1.06 KB

Versions: 3

Compression:

Stored size: 1.06 KB

Contents

# frozen_string_literal: true

require 'rack/request'
require_relative 'reduction'

module Rack
  module Reducer
    # Mount Rack::Reducer as middleware
    # @example A microservice that filters artists
    #   ArtistService = Rack::Builder.new do
    #     use(
    #       Rack::Reducer::Middleware,
    #       dataset: Artist.all,
    #       filters: [
    #         lambda { |name:| where(name: name) },
    #         lambda { |genre:| where(genre: genre) },
    #       ]
    #     )
    #
    #     run ->(env) {  [200, {}, [env['rack.reduction'].to_json]] }
    #   end
    class Middleware
      def initialize(app, options = {})
        @app = app
        @key = options[:key] || 'rack.reduction'
        @reducer = Rack::Reducer.create(options[:dataset], *options[:filters])
      end

      # Call the next app in the middleware stack, with env[key] set
      # to the ouput of a reduction
      def call(env)
        params = Rack::Request.new(env).params
        reduction = @reducer.apply(params)
        @app.call env.merge(@key => reduction)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rack-reducer-1.1.2 lib/rack/reducer/middleware.rb
rack-reducer-1.1.1 lib/rack/reducer/middleware.rb
rack-reducer-1.1.0 lib/rack/reducer/middleware.rb