diff options
Diffstat (limited to 'internal/handler/crud.go')
-rw-r--r-- | internal/handler/crud.go | 103 |
1 files changed, 103 insertions, 0 deletions
diff --git a/internal/handler/crud.go b/internal/handler/crud.go new file mode 100644 index 0000000..4ab0c7f --- /dev/null +++ b/internal/handler/crud.go @@ -0,0 +1,103 @@ +package handler + +import ( + "io" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "go.neonxp.dev/djson/internal/model" + "go.neonxp.dev/json" +) + +func (h *handler) HandleCRUD(r chi.Router) { + r.Use(middleware.CleanPath) + r.Use(middleware.StripSlashes) + + r.Get("/*", func(w http.ResponseWriter, r *http.Request) { + rctx := chi.RouteContext(r.Context()) + res, err := h.core.Get(parsePath(rctx.RoutePath)) + if err != nil { + writeError(http.StatusNotFound, err, w) + return + } + result, err := res.MarshalJSON() + if err != nil { + writeError(http.StatusInternalServerError, err, w) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write(result) + }) + + r.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() + node, err := json.Unmarshal(jsonBody) + if err != nil { + writeError(http.StatusBadRequest, err, w) + return + } + mutation := &model.Mutation{ + Date: time.Now(), + Type: model.Create, + Path: path, + Body: node, + } + if err := h.core.Mutate(r.Context(), mutation); err != nil { + writeError(http.StatusInternalServerError, err, w) + return + } + w.WriteHeader(http.StatusCreated) + }) + + r.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() + node, err := json.Unmarshal(jsonBody) + if err != nil { + writeError(http.StatusBadRequest, err, w) + return + } + mutation := &model.Mutation{ + Date: time.Now(), + Type: model.Merge, + Path: path, + Body: node, + } + if err := h.core.Mutate(r.Context(), mutation); err != nil { + writeError(http.StatusInternalServerError, err, w) + return + } + w.WriteHeader(http.StatusOK) + }) + + r.Delete("/*", func(w http.ResponseWriter, r *http.Request) { + rctx := chi.RouteContext(r.Context()) + path := parsePath(rctx.RoutePath) + mutation := &model.Mutation{ + Date: time.Now(), + Type: model.Remove, + Path: path, + Body: nil, + } + if err := h.core.Mutate(r.Context(), mutation); err != nil { + writeError(http.StatusInternalServerError, err, w) + return + } + w.WriteHeader(http.StatusNoContent) + }) +} |