|
| 1 | +package middleware |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/bcp-innovations/hyperlane-cosmos/util" |
| 6 | +) |
| 7 | + |
| 8 | +// HandleFn is the signature of the Handle function of an Hyperlane application. |
| 9 | +type HandleFn = func(ctx context.Context, mailboxId util.HexAddress, message util.HyperlaneMessage) error |
| 10 | + |
| 11 | +type HandleHookI interface { |
| 12 | + PreHandleHook(ctx context.Context, mailboxID util.HexAddress, message util.HyperlaneMessage) error |
| 13 | + PostHandleHook(ctx context.Context, mailboxID util.HexAddress, message util.HyperlaneMessage) error |
| 14 | +} |
| 15 | + |
| 16 | +type HandleHook struct { |
| 17 | + // preHandleHook is the behavior expected from a type that hook BEFORE executing |
| 18 | + // the Hyperlane application Handle method. |
| 19 | + preHandleFn HandleFn |
| 20 | + |
| 21 | + // postHandleHook is the behavior expected from a type that hook AFTER executing |
| 22 | + // the Hyperlane application Handle method. |
| 23 | + postHandleFn HandleFn |
| 24 | +} |
| 25 | + |
| 26 | +func (h *HandleHook) PreHandleHook(ctx context.Context, mailboxID util.HexAddress, message util.HyperlaneMessage) error { |
| 27 | + if h.preHandleFn != nil { |
| 28 | + return h.preHandleFn(ctx, mailboxID, message) |
| 29 | + } |
| 30 | + |
| 31 | + return nil |
| 32 | +} |
| 33 | + |
| 34 | +func (h *HandleHook) PostHandleHook(ctx context.Context, mailboxID util.HexAddress, message util.HyperlaneMessage) error { |
| 35 | + if h.postHandleFn != nil { |
| 36 | + return h.postHandleFn(ctx, mailboxID, message) |
| 37 | + } |
| 38 | + |
| 39 | + return nil |
| 40 | +} |
| 41 | + |
| 42 | +func NewHandleHook(opts ...HandleHookOpt) *HandleHook { |
| 43 | + h := &HandleHook{} |
| 44 | + |
| 45 | + for _, opt := range opts { |
| 46 | + opt(h) |
| 47 | + } |
| 48 | + return h |
| 49 | +} |
| 50 | + |
| 51 | +type HandleHookOpt func(*HandleHook) |
| 52 | + |
| 53 | +func WithPreHandleHookFn(fn HandleFn) HandleHookOpt { |
| 54 | + return func(h *HandleHook) { |
| 55 | + h.preHandleFn = fn |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +func WithPostHandleFn(fn HandleFn) HandleHookOpt { |
| 60 | + return func(h *HandleHook) { |
| 61 | + h.postHandleFn = fn |
| 62 | + } |
| 63 | +} |
0 commit comments