[#5614] removed hook.HandlerFunc[T] type

This commit is contained in:
Gani Georgiev 2024-10-07 09:52:31 +03:00
parent 1d4dd5d5b4
commit 393b461ea2
13 changed files with 4236 additions and 4235 deletions

View File

@ -1,5 +1,17 @@
## v0.23.0-rc3 (WIP)
> [!CAUTION]
> **This is a prerelease intended for test and experimental purposes only!**
- To avoid confusion and unnecessary casting, the `hook.HandlerFunc[T]` type has been removed and instead everywhere we now use directly the underlying function definition, aka.:
```go
func(T) error
```
## v0.23.0-rc2
> [!CAUTION]
> **This is a prerelease intended for test and experimental purposes only!**
- Small update to the earlier v0.23.0-rc that uses `pb_data/auxiliary.db` instead of `pb_data/aux.db` because it seems that on Windows `aux` is disallowed as file name ([#5607](https://github.com/pocketbase/pocketbase/issues/5607)).

View File

@ -9,7 +9,6 @@ import (
"strings"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/router"
)
@ -50,7 +49,7 @@ func NewRouter(app core.App) (*router.Router[*core.RequestEvent], error) {
}
// WrapStdHandler wraps Go [http.Handler] into a PocketBase handler func.
func WrapStdHandler(h http.Handler) hook.HandlerFunc[*core.RequestEvent] {
func WrapStdHandler(h http.Handler) func(*core.RequestEvent) error {
return func(e *core.RequestEvent) error {
h.ServeHTTP(e.Response, e.Request)
return nil
@ -58,7 +57,7 @@ func WrapStdHandler(h http.Handler) hook.HandlerFunc[*core.RequestEvent] {
}
// WrapStdMiddleware wraps Go [func(http.Handler) http.Handle] into a PocketBase middleware func.
func WrapStdMiddleware(m func(http.Handler) http.Handler) hook.HandlerFunc[*core.RequestEvent] {
func WrapStdMiddleware(m func(http.Handler) http.Handler) func(*core.RequestEvent) error {
return func(e *core.RequestEvent) (err error) {
m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
e.Response = w
@ -99,7 +98,7 @@ func MustSubFS(fsys fs.FS, dir string) fs.FS {
//
// fsys := os.DirFS("./pb_public")
// router.GET("/files/{path...}", apis.Static(fsys, false))
func Static(fsys fs.FS, indexFallback bool) hook.HandlerFunc[*core.RequestEvent] {
func Static(fsys fs.FS, indexFallback bool) func(*core.RequestEvent) error {
if fsys == nil {
panic("Static: the provided fs.FS argument is nil")
}

View File

@ -7,7 +7,6 @@ import (
"strings"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/router"
)
@ -21,7 +20,7 @@ func stripWildcard(pattern string) string {
// installerRedirect redirects the user to the installer dashboard UI page
// when the application needs some preliminary configurations to be done.
func installerRedirect(app core.App, cpPath string) hook.HandlerFunc[*core.RequestEvent] {
func installerRedirect(app core.App, cpPath string) func(*core.RequestEvent) error {
// note: to avoid locks contention it is not concurrent safe but it
// is expected to be updated only once during initialization
var hasSuperuser bool
@ -108,7 +107,7 @@ func installerRedirect(app core.App, cpPath string) hook.HandlerFunc[*core.Reque
//
// Note: intended to be registered only for the dashboard route
// to prevent excessive checks for every other route in installerRedirect.
func dashboardRemoveInstallerParam() hook.HandlerFunc[*core.RequestEvent] {
func dashboardRemoveInstallerParam() func(*core.RequestEvent) error {
return func(e *core.RequestEvent) error {
_, hasInstallerParam := e.Request.URL.Query()[installerParam]
if !hasInstallerParam {
@ -127,7 +126,7 @@ func dashboardRemoveInstallerParam() hook.HandlerFunc[*core.RequestEvent] {
// dashboardCacheControl adds default Cache-Control header for all
// dashboard UI resources (ignoring the root index.html path)
func dashboardCacheControl() hook.HandlerFunc[*core.RequestEvent] {
func dashboardCacheControl() func(*core.RequestEvent) error {
return func(e *core.RequestEvent) error {
if e.Request.PathValue(StaticWildcardParam) != "" {
e.Response.Header().Set("Cache-Control", "max-age=1209600, stale-while-revalidate=86400")

View File

@ -81,7 +81,7 @@ func RequireAuth(optCollectionNames ...string) *hook.Handler[*core.RequestEvent]
}
}
func requireAuth(optCollectionNames ...string) hook.HandlerFunc[*core.RequestEvent] {
func requireAuth(optCollectionNames ...string) func(*core.RequestEvent) error {
return func(e *core.RequestEvent) error {
if e.Auth == nil {
return e.UnauthorizedError("The request requires valid record authorization token.", nil)

View File

@ -19,7 +19,6 @@ import (
"strings"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
)
const (
@ -125,7 +124,7 @@ var DefaultCORSConfig = CORSConfig{
}
// CORSWithConfig returns a CORS middleware with config.
func CORSWithConfig(config CORSConfig) hook.HandlerFunc[*core.RequestEvent] {
func CORSWithConfig(config CORSConfig) func(e *core.RequestEvent) error {
// Defaults
if len(config.AllowOrigins) == 0 {
config.AllowOrigins = DefaultCORSConfig.AllowOrigins

View File

@ -18,7 +18,6 @@ import (
"sync"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/hook"
"github.com/pocketbase/pocketbase/tools/router"
)
@ -47,12 +46,12 @@ type GzipConfig struct {
}
// Gzip returns a middleware which compresses HTTP response using gzip compression scheme.
func Gzip() hook.HandlerFunc[*core.RequestEvent] {
func Gzip() func(*core.RequestEvent) error {
return GzipWithConfig(GzipConfig{})
}
// GzipWithConfig returns a middleware which compresses HTTP response using gzip compression scheme.
func GzipWithConfig(config GzipConfig) hook.HandlerFunc[*core.RequestEvent] {
func GzipWithConfig(config GzipConfig) func(*core.RequestEvent) error {
if config.Level < -2 || config.Level > 9 { // these are consts: gzip.HuffmanOnly and gzip.BestCompression
panic(errors.New("invalid gzip level"))
}

View File

@ -175,13 +175,13 @@ func routerBinds(app core.App, loader *goja.Runtime, executors *vmsPool) {
})
}
func wrapHandlerFunc(executors *vmsPool, handler goja.Value) (hook.HandlerFunc[*core.RequestEvent], error) {
func wrapHandlerFunc(executors *vmsPool, handler goja.Value) (func(*core.RequestEvent) error, error) {
if handler == nil {
return nil, errors.New("handler must be non-nil")
}
switch h := handler.Export().(type) {
case hook.HandlerFunc[*core.RequestEvent]:
case func(*core.RequestEvent) error:
// "native" handler func - no need to wrap
return h, nil
case func(goja.FunctionCall) goja.Value, string:
@ -228,7 +228,7 @@ func wrapMiddlewares(executors *vmsPool, rawMiddlewares ...goja.Value) ([]*hook.
case *hook.Handler[*core.RequestEvent]:
// "native" middleware handler - no need to wrap
wrappedMiddlewares[i] = v
case hook.HandlerFunc[*core.RequestEvent]:
case func(*core.RequestEvent) error:
// "native" middleware func - wrap as handler
wrappedMiddlewares[i] = &hook.Handler[*core.RequestEvent]{
Func: v,
@ -717,7 +717,7 @@ func apisBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$apis", obj)
obj.Set("static", func(dir string, indexFallback bool) hook.HandlerFunc[*core.RequestEvent] {
obj.Set("static", func(dir string, indexFallback bool) func(*core.RequestEvent) error {
return apis.Static(os.DirFS(dir), indexFallback)
})

File diff suppressed because it is too large Load Diff

View File

@ -7,9 +7,6 @@ import (
"github.com/pocketbase/pocketbase/tools/security"
)
// HandlerFunc defines a hook handler function.
type HandlerFunc[T Resolver] func(e T) error
// Handler defines a single Hook handler.
// Multiple handlers can share the same id.
// If Id is not explicitly set it will be autogenerated by Hook.Add and Hook.AddHandler.
@ -18,7 +15,7 @@ type Handler[T Resolver] struct {
//
// Note that users need to call e.Next() in order to proceed with
// the execution of the hook chain.
Func HandlerFunc[T]
Func func(T) error
// Id is the unique identifier of the handler.
//
@ -111,7 +108,7 @@ func (h *Hook[T]) Bind(handler *Handler[T]) string {
// The registered handler is added with a default 0 priority and the id will be autogenerated.
//
// If you want to register a handler with custom priority or id use the [Hook.Bind] method.
func (h *Hook[T]) BindFunc(fn HandlerFunc[T]) string {
func (h *Hook[T]) BindFunc(fn func(T) error) string {
return h.Bind(&Handler[T]{Func: fn})
}
@ -151,9 +148,9 @@ func (h *Hook[T]) Length() int {
// handlers that will be temporary appended to the handlers queue.
//
// NB! Each hook handler must call event.Next() in order the hook chain to proceed.
func (h *Hook[T]) Trigger(event T, oneOffHandlers ...HandlerFunc[T]) error {
func (h *Hook[T]) Trigger(event T, oneOffHandlers ...func(T) error) error {
h.mu.RLock()
handlers := make([]HandlerFunc[T], 0, len(h.handlers)+len(oneOffHandlers))
handlers := make([]func(T) error, 0, len(h.handlers)+len(oneOffHandlers))
for _, handler := range h.handlers {
handlers = append(handlers, handler.Func)
}

View File

@ -124,12 +124,12 @@ func TestHookTriggerErrorPropagation(t *testing.T) {
scenarios := []struct {
name string
handlers []HandlerFunc[*Event]
handlers []func(*Event) error
expectedError error
}{
{
"without error",
[]HandlerFunc[*Event]{
[]func(*Event) error{
func(e *Event) error { return e.Next() },
func(e *Event) error { return e.Next() },
},
@ -137,7 +137,7 @@ func TestHookTriggerErrorPropagation(t *testing.T) {
},
{
"with error",
[]HandlerFunc[*Event]{
[]func(*Event) error{
func(e *Event) error { return e.Next() },
func(e *Event) error { e.Next(); return err },
func(e *Event) error { return e.Next() },

View File

@ -73,7 +73,7 @@ func (h *TaggedHook[T]) Bind(handler *Handler[T]) string {
//
// It is similar to [Hook.Bind] with the difference that the handler
// function is invoked only if the event data tags satisfy h.CanTriggerOn.
func (h *TaggedHook[T]) BindFunc(fn HandlerFunc[T]) string {
func (h *TaggedHook[T]) BindFunc(fn func(T) error) string {
return h.mainHook.BindFunc(func(e T) error {
if h.CanTriggerOn(e.Tags()) {
return fn(e)

View File

@ -46,7 +46,7 @@ func (group *RouterGroup[T]) Group(prefix string) *RouterGroup[T] {
//
// If you need to specify a named middleware (ex. so that it can be removed)
// or middleware with custom exec prirority, use [Group.Bind] method.
func (group *RouterGroup[T]) BindFunc(middlewareFuncs ...hook.HandlerFunc[T]) *RouterGroup[T] {
func (group *RouterGroup[T]) BindFunc(middlewareFuncs ...func(T) error) *RouterGroup[T] {
for _, m := range middlewareFuncs {
group.Middlewares = append(group.Middlewares, &hook.Handler[T]{Func: m})
}
@ -115,7 +115,7 @@ func (group *RouterGroup[T]) Unbind(middlewareIds ...string) *RouterGroup[T] {
// meaning that only a top level group route could have HOST as part of the prefix.
//
// Returns the newly created route to allow attaching route-only middlewares.
func (group *RouterGroup[T]) Route(method string, path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) Route(method string, path string, action func(T) error) *Route[T] {
route := &Route[T]{
Method: method,
Path: path,
@ -128,42 +128,42 @@ func (group *RouterGroup[T]) Route(method string, path string, action hook.Handl
}
// Any is a shorthand for [Group.AddRoute] with "" as route method (aka. matches any method).
func (group *RouterGroup[T]) Any(path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) Any(path string, action func(T) error) *Route[T] {
return group.Route("", path, action)
}
// GET is a shorthand for [Group.AddRoute] with GET as route method.
func (group *RouterGroup[T]) GET(path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) GET(path string, action func(T) error) *Route[T] {
return group.Route(http.MethodGet, path, action)
}
// POST is a shorthand for [Group.AddRoute] with POST as route method.
func (group *RouterGroup[T]) POST(path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) POST(path string, action func(T) error) *Route[T] {
return group.Route(http.MethodPost, path, action)
}
// DELETE is a shorthand for [Group.AddRoute] with DELETE as route method.
func (group *RouterGroup[T]) DELETE(path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) DELETE(path string, action func(T) error) *Route[T] {
return group.Route(http.MethodDelete, path, action)
}
// PATCH is a shorthand for [Group.AddRoute] with PATCH as route method.
func (group *RouterGroup[T]) PATCH(path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) PATCH(path string, action func(T) error) *Route[T] {
return group.Route(http.MethodPatch, path, action)
}
// PUT is a shorthand for [Group.AddRoute] with PUT as route method.
func (group *RouterGroup[T]) PUT(path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) PUT(path string, action func(T) error) *Route[T] {
return group.Route(http.MethodPut, path, action)
}
// HEAD is a shorthand for [Group.AddRoute] with HEAD as route method.
func (group *RouterGroup[T]) HEAD(path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) HEAD(path string, action func(T) error) *Route[T] {
return group.Route(http.MethodHead, path, action)
}
// OPTIONS is a shorthand for [Group.AddRoute] with OPTIONS as route method.
func (group *RouterGroup[T]) OPTIONS(path string, action hook.HandlerFunc[T]) *Route[T] {
func (group *RouterGroup[T]) OPTIONS(path string, action func(T) error) *Route[T] {
return group.Route(http.MethodOptions, path, action)
}

View File

@ -5,7 +5,7 @@ import "github.com/pocketbase/pocketbase/tools/hook"
type Route[T hook.Resolver] struct {
excludedMiddlewares map[string]struct{}
Action hook.HandlerFunc[T]
Action func(T) error
Method string
Path string
Middlewares []*hook.Handler[T]
@ -18,7 +18,7 @@ type Route[T hook.Resolver] struct {
//
// If you need to specify a named middleware (ex. so that it can be removed)
// or middleware with custom exec prirority, use the [Bind] method.
func (route *Route[T]) BindFunc(middlewareFuncs ...hook.HandlerFunc[T]) *Route[T] {
func (route *Route[T]) BindFunc(middlewareFuncs ...func(T) error) *Route[T] {
for _, m := range middlewareFuncs {
route.Middlewares = append(route.Middlewares, &hook.Handler[T]{Func: m})
}