-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core): specify event listener API (#14735)
- Loading branch information
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | ||
} |