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

Add Range example #80

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from all 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
54 changes: 54 additions & 0 deletions examples/range_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package examples_test

import (
"fmt"

"github.com/mfcochauxlaberge/jsonapi"
)

func ExampleRange() {
// The Range function allows pagination to be performed
// on any type that implements the Collection interface.

// Here is a simple collection with some items.
col := jsonapi.Resources{}
col.Add(jsonapi.Wrap(User{
ID: "u1",
Username: "rob",
}))
col.Add(jsonapi.Wrap(User{
ID: "u2",
Username: "arthur",
}))
col.Add(jsonapi.Wrap(User{
ID: "u2",
Username: "henry",
}))
col.Add(jsonapi.Wrap(User{
ID: "u2",
Username: "thisguy",
}))

// The proper parameters are given to Range to get the
// desired page.
page := jsonapi.Range(
&col, // Collection
[]string{"u1", "u2", "u3"}, // Only include resources with thos IDs
nil, // Filter (empty here, see filter example)
[]string{"username", "id"}, // Order in which fields are considered for sorting
2, // Number of elements in the page
1, // Page number, 1 being the first page
)

// To sort resources, the given fields are used in the
// order they appear. The first field is used first, and
// the follwing ones are used only when needed to break
// an equality with the previous field. Missing fields
// are appended to the slice in alphabetical order, except
// for "id" which will always be appended last unless it
// appears in the original slice.

fmt.Printf("Len: %d\n", page.Len())
// Output: 11
// fmt.Printf("%s\n%s\n", page.At(0).GetID(), page.At(1).GetID())
}