-
Notifications
You must be signed in to change notification settings - Fork 0
/
cursor.go
39 lines (33 loc) · 907 Bytes
/
cursor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package firebasetools
import (
"encoding/base64"
"fmt"
"log"
"github.com/vmihailenco/msgpack"
)
// Cursor represents an opaque "position" for a record, for use in pagination
type Cursor struct {
Offset int `json:"offset"`
}
// NewCursor creates a cursor from an offset and ID
func NewCursor(offset int) *Cursor {
return &Cursor{Offset: offset}
}
// EncodeCursor converts a cursor to a string
func EncodeCursor(cursor *Cursor) string {
b, err := msgpack.Marshal(cursor)
if err != nil {
msg := fmt.Sprintf("unable to encode cursor: %s", err)
log.Println(msg)
return msg
}
return base64.StdEncoding.EncodeToString(b)
}
// CreateAndEncodeCursor creates a cursor and immediately encodes it.
// It panics if it cannot encode the cursor.
// These cursors use ZERO BASED indexing.
func CreateAndEncodeCursor(offset int) *string {
c := NewCursor(offset)
enc := EncodeCursor(c)
return &enc
}