Skip to content

Commit

Permalink
feat(core): specify event listener API (#14735)
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronc authored Jan 24, 2023
1 parent 8dbdfea commit e822585
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
32 changes: 32 additions & 0 deletions core/appmodule/event.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package appmodule

import (
"context"

"google.golang.org/protobuf/runtime/protoiface"
)

// HasEventListeners is the extension interface that modules should implement to register
// event listeners.
type HasEventListeners interface {
AppModule

// RegisterEventListeners registers the module's events listeners.
RegisterEventListeners(registrar *EventListenerRegistrar)
}

// EventListenerRegistrar allows registering event listeners.
type EventListenerRegistrar struct {
listeners []any
}

// GetListeners gets the event listeners that have been registered
func (e *EventListenerRegistrar) GetListeners() []any {
return e.listeners
}

// RegisterEventListener registers an event listener for event type E. If a non-nil error is returned by the listener,
// it will cause the process which emitted the event to fail.
func RegisterEventListener[E protoiface.MessageV1](registrar *EventListenerRegistrar, listener func(context.Context, E) error) {
registrar.listeners = append(registrar.listeners, listener)
}
17 changes: 17 additions & 0 deletions core/appmodule/event_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package appmodule

import (
"context"
"reflect"
"testing"

"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
)

func TestEventListenerRegistrar(t *testing.T) {
registrar := &EventListenerRegistrar{}
RegisterEventListener(registrar, func(ctx context.Context, dummy *timestamppb.Timestamp) error { return nil })
require.Len(t, registrar.listeners, 1)
require.Equal(t, reflect.Func, reflect.TypeOf(registrar.listeners[0]).Kind())
}

0 comments on commit e822585

Please sign in to comment.