Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: show pagination #261

Merged
merged 4 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion internal/output/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,16 @@ type PlaintextOutputFn func(resource) string
// We're trading off type safety for easy of use instead of defining a type for each expected resource.
type resource map[string]interface{}

type link map[string]string

type links map[string]link

// resources is the subset of data we need to display a command's plain text response for a list
// of resources.
type resources struct {
Items []resource `json:"items"`
Items []resource `json:"items"`
Links links `json:"_links"`
TotalCount int `json:"totalCount"`
}

// CmdOutputSingular builds a command response based on the flag the user provided and the shape of
Expand Down
68 changes: 48 additions & 20 deletions internal/output/resource_output.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package output
import (
"encoding/json"
"fmt"
"math"
"net/url"
"strconv"
"strings"

"github.com/pkg/errors"
Expand Down Expand Up @@ -45,35 +48,60 @@ func CmdOutput(action string, outputKind string, input []byte) (string, error) {
// no success message
}

if isMultipleResponse {
if len(maybeResources.Items) == 0 {
return "No items found", nil
}
if !isMultipleResponse {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reversed this check to remove the indentation.

return plaintextOutput(SingularPlaintextOutputFn(maybeResource), successMessage+" "), nil
}

// the response could have various properties we want to show
keyExists := func(key string) bool { _, ok := maybeResources.Items[0][key]; return ok }
outputFn := MultiplePlaintextOutputFn
switch {
case keyExists("email"):
outputFn = MultipleEmailPlaintextOutputFn
case keyExists("_id"):
outputFn = MultipleIDPlaintextOutputFn
}
if len(maybeResources.Items) == 0 {
return "No items found", nil
}

items := make([]string, 0, len(maybeResources.Items))
for _, i := range maybeResources.Items {
items = append(items, outputFn(i))
}
// the response could have various properties we want to show
keyExists := func(key string) bool { _, ok := maybeResources.Items[0][key]; return ok }
outputFn := MultiplePlaintextOutputFn
switch {
case keyExists("email"):
outputFn = MultipleEmailPlaintextOutputFn
case keyExists("_id"):
outputFn = MultipleIDPlaintextOutputFn
}

return plaintextOutput("\n"+strings.Join(items, "\n"), successMessage), nil
items := make([]string, 0, len(maybeResources.Items))
for _, i := range maybeResources.Items {
items = append(items, outputFn(i))
}

return plaintextOutput(SingularPlaintextOutputFn(maybeResource), successMessage), nil
var (
pagination string
limit int
offset int
)
self, ok := maybeResources.Links["self"]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This gets the pagination values from the HATEOAS "self" link.

if ok && maybeResources.TotalCount > 0 {
selfURL, _ := url.Parse(self["href"])
limit, _ = strconv.Atoi(selfURL.Query().Get("limit"))
offset, _ = strconv.Atoi(selfURL.Query().Get("offset"))
maxResults := int(math.Min(float64(offset+limit), float64(maybeResources.TotalCount)))
pagination = fmt.Sprintf(
"\nShowing results %d - %d of %d.",
offset+1,
maxResults,
maybeResources.TotalCount,
)
if offset+limit < maybeResources.TotalCount {
pagination += fmt.Sprintf(" Use --offset %d for additional results.", offset+limit)
}
}

if successMessage != "" {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to do some newline + space manipulation to make things work for a single response and multiple responses. We should refactor this to make it easier to reason about.

successMessage += "\n"
}
return plaintextOutput(strings.Join(items, "\n"), successMessage) + pagination, nil
}

func plaintextOutput(out string, successMessage string) string {
if successMessage != "" {
return fmt.Sprintf("%s %s", successMessage, out)
return fmt.Sprintf("%s%s", successMessage, out)
}

return out
Expand Down
93 changes: 89 additions & 4 deletions internal/output/resource_output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,91 @@ import (
)

func TestCmdOutput(t *testing.T) {
// with no additional pagination - does not show offset help
t.Run("with paginated multiple resources", func(t *testing.T) {
input := `{
"_links": {
"self": {
"href": "/my-resources?limit=5",
"type": "application/json"
}
},
"items": [
{
"key": "test-key",
"name": "test-name"
}
],
"totalCount": 100
}`

t.Run("shows pagination", func(t *testing.T) {
expected := "* test-name (test-key)"
expected += "\nShowing results 1 - 5 of 100. Use --offset 5 for additional results."

result, err := output.CmdOutput("list", "plaintext", []byte(input))

require.NoError(t, err)
assert.Equal(t, expected, result)
})
})

t.Run("with a paginated offset shows pagination", func(t *testing.T) {
input := `{
"_links": {
"self": {
"href": "/my-resources?limit=5&offset=5",
"type": "application/json"
}
},
"items": [
{
"key": "test-key",
"name": "test-name"
}
],
"totalCount": 100
}`

t.Run("shows pagination", func(t *testing.T) {
expected := "* test-name (test-key)"
expected += "\nShowing results 6 - 10 of 100. Use --offset 10 for additional results."

result, err := output.CmdOutput("list", "plaintext", []byte(input))

require.NoError(t, err)
assert.Equal(t, expected, result)
})
})

t.Run("with no additional pagination does not show offset help", func(t *testing.T) {
input := `{
"_links": {
"self": {
"href": "/my-resources?limit=5&offset=95",
"type": "application/json"
}
},
"items": [
{
"key": "test-key",
"name": "test-name"
}
],
"totalCount": 100
}`

t.Run("shows pagination", func(t *testing.T) {
expected := "* test-name (test-key)"
expected += "\nShowing results 96 - 100 of 100."

result, err := output.CmdOutput("list", "plaintext", []byte(input))

require.NoError(t, err)
assert.Equal(t, expected, result)
})
})

t.Run("with multiple resources with an ID and name", func(t *testing.T) {
input := `{
"items": [
Expand All @@ -23,8 +108,8 @@ func TestCmdOutput(t *testing.T) {
}`

t.Run("with plaintext output", func(t *testing.T) {
t.Run("returns a success message", func(t *testing.T) {
expected := "\n* test-name (test-id)"
t.Run("returns a list of resources", func(t *testing.T) {
expected := "* test-name (test-id)"

result, err := output.CmdOutput("list", "plaintext", []byte(input))

Expand Down Expand Up @@ -84,7 +169,7 @@ func TestCmdOutput(t *testing.T) {

t.Run("with plaintext output", func(t *testing.T) {
t.Run("returns a success message", func(t *testing.T) {
expected := "Successfully created \n* test-name (test-key)"
expected := "Successfully created\n* test-name (test-key)"

result, err := output.CmdOutput("create", "plaintext", []byte(input))

Expand Down Expand Up @@ -116,7 +201,7 @@ func TestCmdOutput(t *testing.T) {

t.Run("with plaintext output", func(t *testing.T) {
t.Run("returns a success message", func(t *testing.T) {
expected := "Successfully created \n* test-email (test-id)"
expected := "Successfully created\n* test-email (test-id)"

result, err := output.CmdOutput("create", "plaintext", []byte(input))

Expand Down
Loading