How to extract event data from IntermediateEventRepresentation

68 Views Asked by At

I'm writing a context aware upcaster that should extract event data from an IntermediateEventRepresentation and store it in context.

I see that IntermediateEventRepresentation has a getData method which returns SerializedObject<?>. SerializedObject has a getData method that returns T, but this return type doesn't contain the event data I expect.

class MyUpcaster : ContextAwareSingleEventUpcaster<Context>() {
    override fun doUpcast(intermediateRepresentation: IntermediateEventRepresentation, context: Context): IntermediateEventRepresentation {
        val eventData: MyEventType = intermediateRepresentation.data.data  // error
        val eventData: MyEventType = intermediateRepresentation.getData(MyEventType::class.java).data  // error
    }
}
1

There are 1 best solutions below

0
Providen On

Updated Answer

TLDR - I was passing the wrong class as an argument to IntermediateEventRepresentation.getData(). I needed to pass JsonNode::class.java rather than MyEventType::class.java.


My original idea of deserializing to MyEventType proved misguided. If MyEventType ever changes, or if it contains nested objects that change, you'll end up needing to maintain a record of all those object structures within your upcaster, which is undesirable.

It seems better just to work with the JsonNode returned from IntermediateEventRepresentation.getData(JsonNode::class.java).data:

class MyUpcaster() : ContextAwareSingleEventUpcaster<Context>() {
    override fun doUpcast(intermediateRepresentation: IntermediateEventRepresentation, context: Context): IntermediateEventRepresentation {
        val eventJson: JsonNode = intermediateRepresentation.getData(JsonNode::class.java).data
        val key = eventJson.get("id").textValue()
        context.put(key, eventJson) // hooray!
    }
}

Original Answer (Bad)

The SerializedObject returned by IntermediateEventRepresentation.getData() must be (surprise!) deserialized using the appropriate serializer (JacksonSerializer, in this case):

class MyUpcaster(private val serializer: Serializer) : ContextAwareSingleEventUpcaster<Context>() {
    override fun doUpcast(intermediateRepresentation: IntermediateEventRepresentation, context: Context): IntermediateEventRepresentation {
        val eventData: MyEventType = serializer.deserialize(intermediateRepresentation.getData(JsonNode::class.java))
        context.put(eventData.key, eventData.value) // hooray!
    }
}

Important Caveat: This only works if the structure of MyEventType does not change, which cannot be guaranteed.