From 4c058fe8e84f59824a568d21812b933f3759a4da Mon Sep 17 00:00:00 2001 From: rood_ni <41773436+roodni@users.noreply.github.com> Date: Tue, 28 May 2024 16:35:17 +0900 Subject: [PATCH] Add DeleteGraphDef to graph-defs API --- graph_defs.go | 8 ++++++++ graph_defs_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/graph_defs.go b/graph_defs.go index f27ff97..0eac93c 100644 --- a/graph_defs.go +++ b/graph_defs.go @@ -1,5 +1,7 @@ package mackerel +import "net/http" + // GraphDefsParam parameters for posting graph definitions type GraphDefsParam struct { Name string `json:"name"` @@ -20,3 +22,9 @@ func (c *Client) CreateGraphDefs(graphDefs []*GraphDefsParam) error { _, err := requestPost[any](c, "/api/v0/graph-defs/create", graphDefs) return err } + +// DeleteGraphDef deletes a graph definition. +func (c *Client) DeleteGraphDef(name string) error { + _, err := requestJSON[any](c, http.MethodDelete, "/api/v0/graph-defs/delete", map[string]string{"name": name}) + return err +} diff --git a/graph_defs_test.go b/graph_defs_test.go index 9a3d1c4..d24c5db 100644 --- a/graph_defs_test.go +++ b/graph_defs_test.go @@ -99,3 +99,41 @@ func TestGraphDefsOmitJSON(t *testing.T) { t.Errorf("json.Marshal(%#v) = %q; want %q", g, s, want) } } + +func TestDeleteGraphDef(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + if req.URL.Path != "/api/v0/graph-defs/delete" { + t.Error("request URL should be /api/v0/graph-defs/delete but:", req.URL.Path) + } + + if req.Method != "DELETE" { + t.Error("request method should be DELETE but: ", req.Method) + } + body, _ := io.ReadAll(req.Body) + + var data struct { + Name string `json:"name"` + } + + err := json.Unmarshal(body, &data) + if err != nil { + t.Fatal("request body should be decoded as json", string(body)) + } + + if data.Name != "mackerel" { + t.Errorf("request sends json including name but: %s", data.Name) + } + + respJSON, _ := json.Marshal((map[string]bool{"success": true})) + res.Header()["Content-Type"] = []string{"application/json"} + fmt.Fprint(res, string(respJSON)) + })) + defer ts.Close() + + client, _ := NewClientWithOptions("dummy-key", ts.URL, false) + err := client.DeleteGraphDef("mackerel") + + if err != nil { + t.Error("err should be nil but: ", err) + } +}