summaryrefslogtreecommitdiff
path: root/internal/handler/crud.go
blob: b12f68a682f268da321e106d151e91ed46e7d8d4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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)
	})
}