Class: Rubyists::Leopard::MessageWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/leopard/message_wrapper.rb

Overview

Wraps a raw NATS message with parsed payload and convenience response helpers.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nats_msg) ⇒ MessageWrapper

Returns a new instance of MessageWrapper.

Parameters:

  • nats_msg (NATS::Message)

    The NATS message to wrap.



24
25
26
27
28
# File 'lib/leopard/message_wrapper.rb', line 24

def initialize(nats_msg)
  @raw     = nats_msg
  @data    = parse_data(nats_msg.data)
  @headers = nats_msg.header.to_h
end

Instance Attribute Details

#dataNATS::Message, Object (readonly)

Returns:

  • (NATS::Message)

    The original NATS message.

  • (Object)

    The parsed data from the NATS message.



16
# File 'lib/leopard/message_wrapper.rb', line 16

attr_reader :raw, :data

#headersHash

Returns The headers from the NATS message.

Returns:

  • (Hash)

    The headers from the NATS message.



21
22
23
# File 'lib/leopard/message_wrapper.rb', line 21

def headers
  @headers
end

#rawNATS::Message, Object (readonly)

Returns:

  • (NATS::Message)

    The original NATS message.

  • (Object)

    The parsed data from the NATS message.



16
17
18
# File 'lib/leopard/message_wrapper.rb', line 16

def raw
  @raw
end

Instance Method Details

#parse_data(raw) ⇒ Object (private)

Parses the raw data from the NATS message. Assumes the data is in JSON format. If parsing fails, it returns the raw string.

Parameters:

  • raw (String)

    The raw data from the NATS message.

Returns:

  • (Object)

    The parsed data, or the raw string if parsing fails.



54
55
56
57
58
# File 'lib/leopard/message_wrapper.rb', line 54

def parse_data(raw)
  JSON.parse(raw)
rescue JSON::ParserError
  raw
end

#respond(payload) ⇒ void

This method returns an undefined value.

Parameters:

  • payload (Object)

    The payload to respond with.



33
34
35
36
# File 'lib/leopard/message_wrapper.rb', line 33

def respond(payload)
  raw.header = headers unless headers.empty?
  raw.respond(serialize(payload))
end

#respond_with_error(err) ⇒ void

This method returns an undefined value.

Parameters:

  • err (Object)

    The error payload to respond with.



41
42
43
# File 'lib/leopard/message_wrapper.rb', line 41

def respond_with_error(err, &)
  raw.respond_with_error(err, &)
end

#serialize(obj) ⇒ String (private)

Serializes the object to a JSON string if it is not already a string.

Parameters:

  • obj (Object)

    The object to serialize.

Returns:

  • (String)

    The serialized JSON string or the original string.



64
65
66
# File 'lib/leopard/message_wrapper.rb', line 64

def serialize(obj)
  obj.is_a?(String) ? obj : JSON.generate(obj)
end