diff --git a/snapshot.go b/snapshot.go new file mode 100644 index 00000000..8cea9a5c --- /dev/null +++ b/snapshot.go @@ -0,0 +1,37 @@ +package gapi + +import ( + "bytes" + "encoding/json" +) + +// Snapshot represents a Grafana snapshot. +type Snapshot struct { + Model map[string]interface{} `json:"dashboard"` + Expires int64 `json:"expires"` +} + +// SnapshotResponse represents the Grafana API response to creating a dashboard. +type SnapshotCreateResponse struct { + DeleteKey string `json:"deleteKey"` + DeleteURL string `json:"deleteUrl"` + Key string `json:"key"` + URL string `json:"url"` + ID int64 `json:"id"` +} + +// NewSnapshot creates a new Grafana snapshot. +func (c *Client) NewSnapshot(snapshot Snapshot) (*SnapshotCreateResponse, error) { + data, err := json.Marshal(snapshot) + if err != nil { + return nil, err + } + + result := &SnapshotCreateResponse{} + err = c.request("POST", "/api/snapshots", nil, bytes.NewBuffer(data), &result) + if err != nil { + return nil, err + } + + return result, err +} diff --git a/snapshot_test.go b/snapshot_test.go new file mode 100644 index 00000000..c69803da --- /dev/null +++ b/snapshot_test.go @@ -0,0 +1,48 @@ +package gapi + +import ( + "testing" + + "github.com/gobs/pretty" +) + +const ( + createdSnapshotResponse = `{ + "deleteKey":"XXXXXXX", + "deleteUrl":"myurl/api/snapshots-delete/XXXXXXX", + "key":"YYYYYYY", + "url":"myurl/dashboard/snapshot/YYYYYYY", + "id": 1 + }` +) + +func TestSnapshotCreate(t *testing.T) { + server, client := gapiTestTools(t, 200, createdSnapshotResponse) + defer server.Close() + + snapshot := Snapshot{ + Model: map[string]interface{}{ + "title": "test", + }, + Expires: 3600, + } + + resp, err := client.NewSnapshot(snapshot) + if err != nil { + t.Fatal(err) + } + + t.Log(pretty.PrettyFormat(resp)) + + if resp.DeleteKey != "XXXXXXX" { + t.Errorf("Invalid key - %s, Expected %s", resp.DeleteKey, "XXXXXXX") + } + + for _, code := range []int{400, 401, 403, 412} { + server.code = code + _, err = client.NewSnapshot(snapshot) + if err == nil { + t.Errorf("%d not detected", code) + } + } +}