Add sorting and limit to store's List

master
Bel LaPointe 2018-10-09 18:28:55 -06:00
parent 38e1fc44d3
commit d216949d91
3 changed files with 14 additions and 5 deletions

View File

@ -32,7 +32,10 @@ func (bc *BoltClient) Set(namespace, key string, value []byte) error {
})
}
func (bc *BoltClient) List(namespace, key string) ([]string, error) {
func (bc *BoltClient) List(namespace, key string, asc bool, limit int) ([]string, error) {
if limit < 1 {
limit = 10000
}
found := []string{}
err := bc.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(namespace))
@ -40,8 +43,14 @@ func (bc *BoltClient) List(namespace, key string) ([]string, error) {
return nil
}
c := bucket.Cursor()
for k, _ := c.Seek([]byte(key)); k != nil; k, _ = c.Next() {
found = append(found, string(k))
if asc {
for k, _ := c.Seek([]byte(key)); k != nil && len(found) < limit; k, _ = c.Next() {
found = append(found, string(k))
}
} else {
for k, _ := c.Seek([]byte(key)); k != nil && len(found) < limit; k, _ = c.Next() {
found = append(found, string(k))
}
}
return nil
})

View File

@ -56,7 +56,7 @@ func Test_BoltSetListGet(t *testing.T) {
}
}
if results, err := sc.List(c.ns, c.search); err != nil {
if results, err := sc.List(c.ns, c.search, true, -1); err != nil {
t.Errorf("failed to list bolt: %v", err)
} else if len(results) != c.results {
t.Errorf("failed to list bolt: missing results for %q: %v, expceted %v", c.ns, len(results), len(c.keys))

View File

@ -3,6 +3,6 @@ package store
type Client interface {
Get(string, string) ([]byte, error)
Set(string, string, []byte) error
List(string, string) ([]string, error)
List(string, string, bool, int) ([]string, error)
Close() error
}