swaggest / rest

Web services with OpenAPI and JSON Schema done quick in Go
https://pkg.go.dev/github.com/swaggest/rest
MIT License
362 stars 17 forks source link

Added Execution Hooks around UseCase Interactor #106

Open jh125486 opened 1 year ago

jh125486 commented 1 year ago

So this PR is really two things (sorry):

  1. renaming all interface{} -> any and ioutil deprecations (lots of files changes)
  2. Usecase interactor hooks (nethttp/handler.go and associated test file)

My original intention was to just do the Usecase hooks, but the linter got the best of me :/

Anyways.... I have a need for running hooks after input is processed/validated but before the usecase is run (and the same for after the usecase is run, but before the output is validated). It's a slice of function hooks, that are called before and after useCase.Interact() is called at nethttp/handler.go:135.

vearutop commented 1 year ago

I'm sorry it took me so long to review this PR (it would be easier without cosmetic changes).

It seems the same functionality can be achieved with already existing usecase middlewares.

Here is an example

    s := web.DefaultService()
    s.Wrap(nethttp.UseCaseMiddlewares(usecase.MiddlewareFunc(func(next usecase.Interactor) usecase.Interactor {
        var (
            hasName usecase.HasName
            name    = "unknown"
        )

        if usecase.As(next, &hasName) {
            name = hasName.Name()
        }

        return usecase.Interact(func(ctx context.Context, input, output interface{}) error {
            err := next.Interact(ctx, input, output)
            if err != nil {
                log.Printf("usecase %s request (%v) failed: %v\n", name, input, err)
            }

            return err
        })
    })))