homebox/backend/internal/web/adapters/query.go
Hayden 23b5892aef
feat: Notifiers CRUD (#337)
* introduce scaffold for new models

* wip: shoutrrr wrapper (may remove)

* update schema files

* gen: ent code

* gen: migrations

* go mod tidy

* add group_id to notifier

* db migration

* new mapper helpers

* notifier repo

* introduce experimental adapter pattern for hdlrs

* refactor adapters to fit more common use cases

* new routes for notifiers

* update errors to fix validation panic

* go tidy

* reverse checkbox label display

* wip: notifiers UI

* use badges instead of text

* improve documentation

* add scaffold schema reference

* remove notifier service

* refactor schema folder

* support group edges via scaffold

* delete test file

* include link to API docs

* audit and update documentation + improve format

* refactor schema edges

* refactor

* add custom validator

* set validate + order fields by name

* fix failing tests
2023-03-06 21:18:58 -09:00

72 lines
1.5 KiB
Go

package adapters
import (
"net/http"
"github.com/hay-kot/homebox/backend/pkgs/server"
)
// Query is a server.Handler that decodes a query from the request and calls the provided function.
//
// Example:
//
// type Query struct {
// Foo string `schema:"foo"`
// }
//
// fn := func(ctx context.Context, q Query) (any, error) {
// // do something with q
// return nil, nil
// }
//
// r.Get("/foo", adapters.Query(fn, http.StatusOK))
func Query[T any, Y any](f AdapterFunc[T, Y], ok int) server.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
q, err := decodeQuery[T](r)
if err != nil {
return err
}
res, err := f(r.Context(), q)
if err != nil {
return err
}
return server.Respond(w, ok, res)
}
}
// QueryID is a server.Handler that decodes a query and an ID from the request and calls the provided function.
//
// Example:
//
// type Query struct {
// Foo string `schema:"foo"`
// }
//
// fn := func(ctx context.Context, ID uuid.UUID, q Query) (any, error) {
// // do something with ID and q
// return nil, nil
// }
//
// r.Get("/foo/{id}", adapters.QueryID(fn, http.StatusOK))
func QueryID[T any, Y any](param string, f IDFunc[T, Y], ok int) server.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
ID, err := routeUUID(r, param)
if err != nil {
return err
}
q, err := decodeQuery[T](r)
if err != nil {
return err
}
res, err := f(r.Context(), ID, q)
if err != nil {
return err
}
return server.Respond(w, ok, res)
}
}