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:

src/subscribers/product-created.go
// 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:

src/subscribers/product-created.go
// 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:

Namestring
The name of the triggered event.
Dataany
The data payload of the event. For the events that MedusaGo emits, it's a *dal.Record, and its properties are different for each event.
Metadata*dal.Record
Additional data and context of the emitted event, such as created_at and published_at. It can be nil.

For example, this function reads the details of an event:

src/subscribers/describe-event.go
// 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
}
Note: The payload and the metadata you receive depend on the event module. With the Redis Event Module, they're decoded from JSON, so the payload is always a *dal.Record or a []any. With the Local Event Module, you receive the value that was passed when the event was emitted.
Found a problem with this page?Report Issue
Edited Nov 14·Edit this page