Event Data Payload
In this chapter, you'll learn how subscribers receive an event's data payload.
Access Event's Data Payload#
When events are emitted, they're emitted with a data payload.
The Event value that the subscriber function receives as a parameter holds the event payload in its Data property, with additional context in the Metadata property.
For example:
// productCreatedHandler returns the subscriber of the product.created event.
func productCreatedHandler(container composer.Container) eventbus.Subscriber {
return func(ctx context.Context, event eventbus.Event) error {
logger, _ := container.Resolve(common.ContainerRegistrationKeys.LOGGER).(*slog.Logger)
logger.Info("The product was created", "event", event.Name, "product_id", eventID(event))
return nil
}
}
This logs the product ID received in the product.created event's data payload.
The eventID function in the example reads the id property of the payload. The payload of the events that MedusaGo emits is an object of type *dal.Record, so Data holds a *dal.Record, and you read its values with the Get method:
// eventID reads the id property of an event's payload.
func eventID(event eventbus.Event) string {
// The payload of the events Medusa emits is an object, with the id of the
// resource the event is about.
data, ok := event.Data.(*dal.Record)
if !ok || data == nil {
return ""
}
id, _ := data.Get("id")
s, _ := id.(string)
return s
}
Since Data has the type any, check the type of the payload before you use it. The properties of the payload are different for each event.
The Event struct has the following properties:
NamestringDataany*dal.Record, and its properties are different for each event.Metadata*dal.Recordcreated_at and published_at. It can be nil.For example, this function reads the details of an event:
// describeEvent reads the details of an event.
func describeEvent(event eventbus.Event) (name string, source any, createdAt any) {
// event.Metadata is nil when the event has no metadata.
if event.Metadata != nil {
source, _ = event.Metadata.Get("source")
createdAt, _ = event.Metadata.Get("created_at")
}
return event.Name, source, createdAt
}
*dal.Record or a []any. With the Local Event Module, you receive the value that was passed when the event was emitted.