Skip to content

Serializer Adapters

Ahmad Elassuty edited this page Jan 27, 2021 · 2 revisions

You can configure how events are serialised before they are handed to the delivery backend. This is mainly to provide flexibility on how events are stored and maintain the objects structure on deserialisation. It is also for future flexibility of supporting other types of serialisation, e.g MsgPack.

Json (default)

Json serializer does not require any dependencies. Also it does not keep the object attributes structure:

[1] pry(main)> event = Examples::OrderPlaced.new(uid: 'test', attr_1: 1, attr_2: 2)
=> #<Examples::OrderPlaced:0x00007ff4c7504380
 @correlation_id="e57879c0-f08c-4ed8-bc74-c06f81a0be94",
 @created_at=2021-01-27 20:48:37.345967 +0100,
 @payload={:attr_1=>1, :attr_2=>2},
 @uid="test">
[2] pry(main)> serialized = EventRouter.serialize(event)
=> "{\"uid\":\"test\",\"correlation_id\":\"e57879c0-f08c-4ed8-bc74-c06f81a0be94\",\"payload\":{\"attr_1\":1,\"attr_2\":2},\"created_at\":\"2021-01-27 20:48:37 +0100\",\"er_class\":\"Examples::OrderPlaced\"}"
[3] pry(main)> deserialized = EventRouter.deserialize(serialized)
=> #<Examples::OrderPlaced:0x00007ff4c7383970
 @correlation_id="e57879c0-f08c-4ed8-bc74-c06f81a0be94",
 @created_at="2021-01-27 20:48:37 +0100",
 @payload={"attr_1"=>1, "attr_2"=>2},
 @uid="test">

As you can see, the event.payload hash has changed from symbol keys to string keys after deserialisation. This will impact how you access the payload inside the destination handler method.

Oj on the other hand can retain the attributes types after deserialisation:

[1] pry(main)> event = Examples::OrderPlaced.new(uid: 'test', attr_1: 1, attr_2: 2)
=> #<Examples::OrderPlaced:0x00007fa7dcaf8fd0
 @correlation_id="7571b61c-2258-4265-9d93-0ee922b6f65c",
 @created_at=2021-01-27 20:54:16.008557 +0100,
 @payload={:attr_1=>1, :attr_2=>2},
 @uid="test">
[2] pry(main)> serialized = EventRouter.serialize(event)
=> "{\"^o\":\"Examples::OrderPlaced\",\"uid\":\"test\",\"correlation_id\":\"7571b61c-2258-4265-9d93-0ee922b6f65c\",\"created_at\":{\"^t\":1611777256.008557000},\"payload\":{\":attr_1\":1,\":attr_2\":2}}"
[3] pry(main)> deserialized = EventRouter.deserialize(serialized)
=> #<Examples::OrderPlaced:0x00007fa7dca81ca0
 @correlation_id="7571b61c-2258-4265-9d93-0ee922b6f65c",
 @created_at=2021-01-27 20:54:16.008557 +0100,
 @payload={:attr_1=>1, :attr_2=>2},
 @uid="test">

Define your custom adapter

  • create a new class that inherits from EventRouter::Serializers::Base
class CustomSerializerAdapter < EventRouter::Serializers::Base; end
Clone this wiki locally