Class: Lepus::Producers::Middlewares::JSON

Inherits:
Middleware
  • Object
show all
Defined in:
lib/lepus/producers/middlewares/json.rb

Overview

A middleware that serializes Hash payloads to JSON and sets the content_type.

Instance Method Summary collapse

Constructor Details

#initialize(**opts) ⇒ JSON

Returns a new instance of JSON.

Parameters:

  • opts (Hash)

    The options for the middleware.

Options Hash (**opts):

  • :only_hash (Boolean) — default: true

    Only serialize Hash payloads.



12
13
14
15
# File 'lib/lepus/producers/middlewares/json.rb', line 12

def initialize(**opts)
  super
  @only_hash = opts.fetch(:only_hash, true)
end

Instance Method Details

#call(message, app) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/lepus/producers/middlewares/json.rb', line 17

def call(message, app)
  payload = message.payload

  if should_serialize?(payload)
    serialized_payload = MultiJson.dump(payload)
     = (message., content_type: "application/json")
    message = message.mutate(payload: serialized_payload, metadata: )
  end

  app.call(message)
end