Skip to content

Commit

Permalink
fixup! Implement typed request data using generics
Browse files Browse the repository at this point in the history
  • Loading branch information
nachtjasmin committed Nov 23, 2023
1 parent d1c8032 commit 990afc8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 12 deletions.
19 changes: 12 additions & 7 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package e5e
import (
"context"
"encoding/json"
"fmt"
)

// A Handler responds to a request.
Expand Down Expand Up @@ -39,12 +40,11 @@ func (h handlerFunc[T, TContext]) Handle(ctx context.Context, evt Request[T, TCo
// invoked with a Request[T]) in such a way as to make it non-generic so that it can
// be used in other non-generic code like [Mux].
type handlerFactory interface {
// UnmarshalJob unmarshals the request to the internal state of the factory and returns any errors.
UnmarshalJob(payload []byte) error

// Execute the handler with the internal request state.
// Only called after UnmarshalJob.
Execute(ctx context.Context) (*Result, error)
// Execute the handler with payload, which should be a deserializable JSON object.
// Any errors that occur due to deserialization or otherwise are returned.
//
// It is safe to call this method from multiple goroutines if the underlying [Handler] is.
Execute(ctx context.Context, payload []byte) (*Result, error)
}

type typedHandlerFactory[T, TContext Data] struct {
Expand All @@ -56,6 +56,11 @@ func (t *typedHandlerFactory[T, TContext]) UnmarshalJob(data []byte) error {
return json.Unmarshal(data, &t.request)
}

func (t *typedHandlerFactory[T, TContext]) Execute(ctx context.Context) (*Result, error) {
func (t *typedHandlerFactory[T, TContext]) Execute(ctx context.Context, payload []byte) (*Result, error) {
var request Request[T, TContext]
if err := json.Unmarshal(payload, &request); err != nil {
return nil, fmt.Errorf("unmarshaling JSON failed: %w", err)
}

return t.h.Handle(ctx, t.request)
}
6 changes: 1 addition & 5 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,7 @@ func (m *Mux) execute(ctx context.Context, payload []byte) (string, error) {
}

factory := m.handlers[m.Options.Entrypoint]
if err := factory.UnmarshalJob(payload); err != nil {
return "", fmt.Errorf("unmarshalling request into request: %w", err)
}

res, err := factory.Execute(ctx)
res, err := factory.Execute(ctx, payload)
if err != nil {
return "", fmt.Errorf("handler execution: %w", err)
}
Expand Down

0 comments on commit 990afc8

Please sign in to comment.