firestore_iter.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package firestore
  2. import (
  3. "context"
  4. "errors"
  5. fs "cloud.google.com/go/firestore"
  6. "github.com/kellegous/go/internal"
  7. "google.golang.org/api/iterator"
  8. )
  9. // RouteIterator allows iteration of the named routes in firestore.
  10. type RouteIterator struct {
  11. ctx context.Context
  12. db *fs.Client
  13. it *fs.DocumentIterator
  14. doc *fs.DocumentSnapshot
  15. err error
  16. }
  17. // Valid indicates whether the current values of the iterator are valid.
  18. func (i *RouteIterator) Valid() bool {
  19. return i.db != nil && i.it != nil && i.doc != nil && i.err == nil
  20. }
  21. // Next advances the iterator to the next value.
  22. func (i *RouteIterator) Next() bool {
  23. doc, err := i.it.Next()
  24. if err != nil {
  25. if errors.Is(err, iterator.Done) {
  26. i.doc = nil
  27. } else {
  28. i.err = err
  29. }
  30. return false
  31. }
  32. i.doc = doc
  33. return true
  34. }
  35. // Seek ...
  36. func (i *RouteIterator) Seek(cur string) bool {
  37. // firestore makes this a little hard. Make a whole new
  38. // document iterator that starts at a new spot.
  39. i.it = i.db.Collection("routes").OrderBy(fs.DocumentID, fs.Asc).StartAt(cur).Documents(i.ctx)
  40. doc, err := i.it.Next()
  41. if err != nil {
  42. i.err = err
  43. i.doc = nil
  44. return false
  45. }
  46. i.doc = doc
  47. return true
  48. }
  49. // Error returns any active error that has stopped the iterator.
  50. func (i *RouteIterator) Error() error {
  51. return i.err
  52. }
  53. // Name is the name of the current route.
  54. func (i *RouteIterator) Name() string {
  55. return i.doc.Ref.ID
  56. }
  57. // Route is the current route.
  58. func (i *RouteIterator) Route() *internal.Route {
  59. var rt internal.Route
  60. if err := i.doc.DataTo(&rt); err != nil {
  61. i.err = err
  62. return nil
  63. }
  64. return &rt
  65. }
  66. // Release disposes of the resources in the iterator.
  67. func (i *RouteIterator) Release() {
  68. i.it.Stop()
  69. i.doc = nil
  70. i.err = nil
  71. }