Sha256: 4bbb95dbf039740316ac3fae4fc1e21584334580f2c11fd2a8445289045a41c7

Contents?: true

Size: 1.41 KB

Versions: 36

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

module WaterDrop
  # Simple middleware layer for manipulating messages prior to their validation
  class Middleware
    def initialize
      @mutex = Mutex.new
      @steps = []
    end

    # Runs middleware on a single message prior to validation
    #
    # @param message [Hash] message hash
    # @return [Hash] message hash. Either the same if transformed in place, or a copy if modified
    #   into a new object.
    # @note You need to decide yourself whether you don't use the message hash data anywhere else
    #   and you want to save on memory by modifying it in place or do you want to do a deep copy
    def run(message)
      @steps.each do |step|
        message = step.call(message)
      end

      message
    end

    # @param messages [Array<Hash>] messages on which we want to run middlewares
    # @return [Array<Hash>] transformed messages
    def run_many(messages)
      messages.map do |message|
        run(message)
      end
    end

    # Register given middleware as the first one in the chain
    # @param step [#call] step that needs to return the message
    def prepend(step)
      @mutex.synchronize do
        @steps.prepend step
      end
    end

    # Register given middleware as the last one in the chain
    # @param step [#call] step that needs to return the message
    def append(step)
      @mutex.synchronize do
        @steps.append step
      end
    end
  end
end

Version data entries

36 entries across 36 versions & 1 rubygems

Version Path
waterdrop-2.8.0 lib/waterdrop/middleware.rb
waterdrop-2.7.4 lib/waterdrop/middleware.rb
waterdrop-2.7.3 lib/waterdrop/middleware.rb
waterdrop-2.7.0 lib/waterdrop/middleware.rb
waterdrop-2.7.0.rc2 lib/waterdrop/middleware.rb
waterdrop-2.7.0.rc1 lib/waterdrop/middleware.rb
waterdrop-2.7.0.beta2 lib/waterdrop/middleware.rb
waterdrop-2.7.0.beta1 lib/waterdrop/middleware.rb
waterdrop-2.7.0.alpha3 lib/waterdrop/middleware.rb
waterdrop-2.7.0.alpha2 lib/waterdrop/middleware.rb
waterdrop-2.7.0.alpha1 lib/waterdrop/middleware.rb
waterdrop-2.6.14 lib/waterdrop/middleware.rb
waterdrop-2.6.13 lib/waterdrop/middleware.rb
waterdrop-2.6.12 lib/waterdrop/middleware.rb
waterdrop-2.6.11 lib/waterdrop/middleware.rb
waterdrop-2.6.10 lib/waterdrop/middleware.rb
waterdrop-2.6.9 lib/waterdrop/middleware.rb
waterdrop-2.6.8 lib/waterdrop/middleware.rb
waterdrop-2.6.7 lib/waterdrop/middleware.rb
waterdrop-2.6.6 lib/waterdrop/middleware.rb