Skip to content
This repository was archived by the owner on Jan 15, 2024. It is now read-only.

Commit bdffb25

Browse files
author
Julien Pivotto
authored
Enable snapshot creation (#56)
Signed-off-by: Julien Pivotto <roidelapluie@inuits.eu>
1 parent f65e351 commit bdffb25

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

snapshot.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package gapi
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
)
7+
8+
// Snapshot represents a Grafana snapshot.
9+
type Snapshot struct {
10+
Model map[string]interface{} `json:"dashboard"`
11+
Expires int64 `json:"expires"`
12+
}
13+
14+
// SnapshotResponse represents the Grafana API response to creating a dashboard.
15+
type SnapshotCreateResponse struct {
16+
DeleteKey string `json:"deleteKey"`
17+
DeleteURL string `json:"deleteUrl"`
18+
Key string `json:"key"`
19+
URL string `json:"url"`
20+
ID int64 `json:"id"`
21+
}
22+
23+
// NewSnapshot creates a new Grafana snapshot.
24+
func (c *Client) NewSnapshot(snapshot Snapshot) (*SnapshotCreateResponse, error) {
25+
data, err := json.Marshal(snapshot)
26+
if err != nil {
27+
return nil, err
28+
}
29+
30+
result := &SnapshotCreateResponse{}
31+
err = c.request("POST", "/api/snapshots", nil, bytes.NewBuffer(data), &result)
32+
if err != nil {
33+
return nil, err
34+
}
35+
36+
return result, err
37+
}

snapshot_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package gapi
2+
3+
import (
4+
"testing"
5+
6+
"github.com/gobs/pretty"
7+
)
8+
9+
const (
10+
createdSnapshotResponse = `{
11+
"deleteKey":"XXXXXXX",
12+
"deleteUrl":"myurl/api/snapshots-delete/XXXXXXX",
13+
"key":"YYYYYYY",
14+
"url":"myurl/dashboard/snapshot/YYYYYYY",
15+
"id": 1
16+
}`
17+
)
18+
19+
func TestSnapshotCreate(t *testing.T) {
20+
server, client := gapiTestTools(t, 200, createdSnapshotResponse)
21+
defer server.Close()
22+
23+
snapshot := Snapshot{
24+
Model: map[string]interface{}{
25+
"title": "test",
26+
},
27+
Expires: 3600,
28+
}
29+
30+
resp, err := client.NewSnapshot(snapshot)
31+
if err != nil {
32+
t.Fatal(err)
33+
}
34+
35+
t.Log(pretty.PrettyFormat(resp))
36+
37+
if resp.DeleteKey != "XXXXXXX" {
38+
t.Errorf("Invalid key - %s, Expected %s", resp.DeleteKey, "XXXXXXX")
39+
}
40+
41+
for _, code := range []int{400, 401, 403, 412} {
42+
server.code = code
43+
_, err = client.NewSnapshot(snapshot)
44+
if err == nil {
45+
t.Errorf("%d not detected", code)
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)