From 466731e2cfa9973f38865cf2e80fcb91aab4eedd Mon Sep 17 00:00:00 2001 From: Amolith Date: Tue, 6 Sep 2022 11:44:11 -0400 Subject: [PATCH] finish up pagination support in API and backend --- helperfuncs.go | 44 ++++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/helperfuncs.go b/helperfuncs.go index 2c94a061b8e28d37954b18cca7bac9b40e3e0356..0696847ad34dc8837cd7d93f93c5efa522228c29 100644 --- a/helperfuncs.go +++ b/helperfuncs.go @@ -22,6 +22,7 @@ func (m model) create(name string, url string) string { return txn.Set([]byte(name), []byte(url)) }) if err != nil { + // TODO: return an error instead so it can be handled like an error return fmt.Sprint(err) } @@ -42,24 +43,43 @@ func (m model) read(start string, end string, count int) (map[string]string, err err := m.database.View(func(txn *badger.Txn) error { opts := badger.DefaultIteratorOptions - opts.PrefetchSize = 10 + opts.PrefetchSize = 20 if start != "" && end == "" { + // Start value provided, iterate backwards opts.Reverse = true } iterator := txn.NewIterator(opts) - if start != "" && end == "" { - iterator.Seek([]byte(end)) - } else if start == "" && end != "" { + defer iterator.Close() + if start == "" && end == "" { + iterator.Rewind() + } else if start != "" && end == "" { + // Set position to "start" iterator.Seek([]byte(start)) + // If "start" exists, move to next value + if iterator.Valid() { + iterator.Next() + } + } else if start == "" && end != "" { + // Start value provided, iterate forwards + // Set position to "end" + iterator.Seek([]byte(end)) + // If "end" exists, move to next value + if iterator.Valid() { + iterator.Next() + } + } else { + return errors.New("Only provide start OR end parameters, not both") } - defer iterator.Close() - for iterator.Rewind(); iterator.Valid(); iterator.Next() { - err := iterator.Item().Value(func(v []byte) error { - links[string(iterator.Item().Key())] = string(v) - return nil - }) - if err != nil { - return err + for i := 0; i < count; i++ { + if iterator.Valid() { + err := iterator.Item().Value(func(v []byte) error { + links[string(iterator.Item().Key())] = string(v) + return nil + }) + if err != nil { + return err + } + iterator.Next() } } return nil