Skip to content

Commit

Permalink
Merge pull request #46 from K-Phoen/dash-delete
Browse files Browse the repository at this point in the history
Add a DeleteDashboard method to the client
  • Loading branch information
K-Phoen authored Mar 23, 2020
2 parents 03a6fc5 + ddd39f8 commit b31bdeb
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
32 changes: 32 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,38 @@ func (client *Client) UpsertDashboard(ctx context.Context, folder *Folder, build
return &model, nil
}

// DeleteDashboard deletes a dashboard given its UID.
func (client *Client) DeleteDashboard(ctx context.Context, uid string) error {
resp, err := client.delete(ctx, "/api/dashboards/uid/"+uid)
if err != nil {
return err
}

defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}

return fmt.Errorf("could not delete dashboard: %s", body)
}

return nil
}

func (client Client) delete(ctx context.Context, path string) (*http.Response, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodDelete, client.url(path), nil)
if err != nil {
return nil, err
}

request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", client.apiToken))

return client.http.Do(request)
}

func (client Client) postJSON(ctx context.Context, path string, body []byte) (*http.Response, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodPost, client.url(path), bytes.NewReader(body))
if err != nil {
Expand Down
30 changes: 30 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,33 @@ func TestDashboardsCreationCanFail(t *testing.T) {
req.Error(err)
req.Nil(board)
}

func TestDeleteDashboard(t *testing.T) {
req := require.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, `{"title": "Production Overview"}`)
}))
defer ts.Close()

client := NewClient(http.DefaultClient, ts.URL, "")

err := client.DeleteDashboard(context.TODO(), "some uid")

req.NoError(err)
}

func TestDeleteDashboardCanFail(t *testing.T) {
req := require.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintln(w, `{"message": "oh noes"}`)
}))
defer ts.Close()

client := NewClient(http.DefaultClient, ts.URL, "")

err := client.DeleteDashboard(context.TODO(), "some uid")

req.Error(err)
}

0 comments on commit b31bdeb

Please sign in to comment.