Skip to content

Commit

Permalink
Fixed folder pagination (grafana#134)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jramirezg authored Mar 29, 2023
1 parent 5c6d8c2 commit 303710b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 15 deletions.
28 changes: 22 additions & 6 deletions folder.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"net/url"
)

// Folder represents a Grafana folder.
Expand All @@ -22,13 +23,28 @@ type FolderPayload struct {

// Folders fetches and returns Grafana folders.
func (c *Client) Folders() ([]Folder, error) {
folders := make([]Folder, 0)
err := c.request("GET", "/api/folders/", nil, nil, &folders)
if err != nil {
return folders, err
const limit = 1000
var (
page = 0
newFolders []Folder
folders []Folder
query = make(url.Values)
)
query.Set("limit", fmt.Sprint(limit))
for {
page++
query.Set("page", fmt.Sprint(page))

if err := c.request("GET", "/api/folders/", query, nil, &newFolders); err != nil {
return nil, err
}

folders = append(folders, newFolders...)

if len(newFolders) < limit {
return folders, nil
}
}

return folders, err
}

// Folder fetches and returns the Grafana folder whose ID it's passed.
Expand Down
28 changes: 19 additions & 9 deletions folder_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package gapi

import (
"strings"
"testing"

"github.com/gobs/pretty"
)

const (
getFoldersJSON = `
[
{
getFoldersJSON = `{
"id":1,
"uid": "nErXDvCkzz",
"title": "Departmenet ABC",
Expand All @@ -23,9 +22,7 @@ const (
"updatedBy": "admin",
"updated": "2018-01-31T17:43:12+01:00",
"version": 1
}
]
`
}`
getFolderJSON = `
{
"id":1,
Expand Down Expand Up @@ -85,7 +82,17 @@ const (
)

func TestFolders(t *testing.T) {
client := gapiTestTools(t, 200, getFoldersJSON)
mockData := strings.Repeat(getFoldersJSON+",", 1000) // make 1000 folders.
mockData = "[" + mockData[:len(mockData)-1] + "]" // remove trailing comma; make a json list.

// This creates 1000 + 1000 + 1 (2001, 3 calls) worth of folders.
client := gapiTestToolsFromCalls(t, []mockServerCall{
{200, mockData},
{200, mockData},
{200, "[" + getFolderJSON + "]"},
})

const dashCount = 2001

folders, err := client.Folders()
if err != nil {
Expand All @@ -94,12 +101,15 @@ func TestFolders(t *testing.T) {

t.Log(pretty.PrettyFormat(folders))

if len(folders) != 1 {
t.Error("Length of returned folders should be 1")
if len(folders) != dashCount {
t.Errorf("Length of returned folders should be %d", dashCount)
}
if folders[0].ID != 1 || folders[0].Title != "Departmenet ABC" {
t.Error("Not correctly parsing returned folders.")
}
if folders[dashCount-1].ID != 1 || folders[dashCount-1].Title != "Departmenet ABC" {
t.Error("Not correctly parsing returned folders.")
}
}

func TestFolder(t *testing.T) {
Expand Down

0 comments on commit 303710b

Please sign in to comment.