gogination

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 6, 2021 License: MIT Imports: 3 Imported by: 0

README

gogination

mongodb pagination, written in golang

usage

package example

import (
	"context"
	"time"

	"github.com/rbicker/gogination"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Person struct {
	Name  string `bson:"name"`
	Age   int    `bson:"age"`
	State string `bson:"state"`
}

func main() {
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)

	// connect to mongodb server
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(ctx)

	// set db & collection
	db := client.Database("example")
	col := db.Collection("people")

	// filter, sorting & limit
	filter := bson.D{
		bson.E{
			Key:   "state",
			Value: "Washington",
		},
	}
	sort := bson.D{
		bson.E{
			Key:   "age",
			Value: -1,
		},
	}
	opts := options.Find()
	opts.SetSort(sort)
	opts.SetLimit(10)

	// query
	cur, err := col.Find(ctx, filter, opts)
	if err != nil {
		panic(err)
	}
	var people []Person
	err = cur.All(ctx, people)
	if err != nil {
		panic(err)
	}

	// determine filter for next page
	builder, err := NewBuilder()
	if err != nil {
		panic(err)
	}
	last := people[len(people)-1]
	nextFilter, err := builder.NextFilter(last, filter, sort)
	if err != nil {
		panic(err)
	}

	// todo: encode filter and add to api response
	// ...
}

Documentation

Index

Constants

View Source
const (
	ErrExpectedStruct = constError("struct type object expected")
	ErrNoIdField      = constError("given object does not have an ID field")
	ErrInvalidOrderBy = constError("given order by document is invalid")
)

errors

Variables

This section is empty.

Functions

func WithMongoIdField

func WithMongoIdField(fieldName string) func(*Builder) error

WithMongoIdField sets a custom mongodb id field (default: _id).

func WithStructIdField

func WithStructIdField(fieldName string) func(*Builder) error

WithStructIdField sets a custom id field (default: Id).

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder is a small helper for pagination related to mongodb.

func NewBuilder

func NewBuilder(opts ...func(*Builder)) (*Builder, error)

NewBuilder is a factory method for creating a new builder.

func (*Builder) NextFilter

func (builder *Builder) NextFilter(obj interface{}, filter bson.D, sort bson.D) (bson.D, error)

NextFilter determines the filter to query the next document after the one given as obj. It takes the given filter and orderBy bson documents into consideration. The resulting filter will get returned as a bson document.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL