package handler
import (
"fmt"
"io"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.neonxp.dev/djson/internal/command"
"go.neonxp.dev/objectid"
)
func (h *handler) HandleCRUD(router chi.Router) {
router.Use(middleware.CleanPath)
router.Use(middleware.StripSlashes)
router.Get("/*", func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
path := parsePath(rctx.RoutePath)
node, err := h.core.Query(r.Context(), path)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf(`{"error":"%s"}`, err.Error())))
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(node.String()))
})
router.Post("/*", func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
path := parsePath(rctx.RoutePath)
jsonBody, err := io.ReadAll(r.Body)
if err != nil {
writeError(http.StatusBadRequest, err, w)
return
}
r.Body.Close()
mutation := command.Mutation{
ID: objectid.New(),
Type: command.Create,
Path: path,
Data: string(jsonBody),
}
if err := h.core.Apply(r.Context(), &mutation); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf(`{"error":"%s"}`, err.Error())))
return
}
w.WriteHeader(http.StatusCreated)
})
router.Patch("/*", func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
path := parsePath(rctx.RoutePath)
jsonBody, err := io.ReadAll(r.Body)
if err != nil {
writeError(http.StatusBadRequest, err, w)
return
}
r.Body.Close()
mutation := command.Mutation{
ID: objectid.New(),
Type: command.Merge,
Path: path,
Data: string(jsonBody),
}
if err := h.core.Apply(r.Context(), &mutation); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf(`{"error":"%s"}`, err.Error())))
return
}
w.WriteHeader(http.StatusOK)
})
router.Delete("/*", func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
path := parsePath(rctx.RoutePath)
mutation := command.Mutation{
ID: objectid.New(),
Type: command.Remove,
Path: path,
}
if err := h.core.Apply(r.Context(), &mutation); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf(`{"error":"%s"}`, err.Error())))
return
}
w.WriteHeader(http.StatusNoContent)
})
}