pagination

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2023 License: MIT Imports: 6 Imported by: 0

README

Mongo Pagination

Pagination is a package providing a function (Paginate) that queries the mongo database and return results by pages. It is useful to avoid the processing of too much data.

The pagination follow the rules explained in the Scalingo pagination documentation

How to use it

First, set the default value of number of items per page and the maximum of item by page as the following snippet:

pageService := pagination.NewPaginationService(pagination.ServiceOpts{
	PerPageDefault: 5,
	MaxPerPage:     15,
})

Then call the Paginate as follow:

resultObject := []*ResultObject{}
dbQuery := bson.M{"searched_field": "field_1"}

paginateOpts := PaginateOpts{
    PageNumber:  5,         // Number of the requested page (can be empty, default 1)
    AmountItems: 10,        // Amount of items by page (can be empty)
    Query:       dbQuery,   // Query which will be executed on the database (can be nil)
    SortOrder:   "-_id",    // The field for the sort order (by default "_id")
}

meta, err := pageService.Paginate(
    ctx,                    // A context (required)
    "RequestedCollection",  // Name of the collection (required)
    &resultObject,          // The object that will contain the data (must be an array)
    paginateOpts)

The returned meta object contains pagination metadata that could be used in the request answer.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Meta

type Meta struct {
	CurrentPage int  `json:"current_page"`
	PrevPage    *int `json:"prev_page"`
	NextPage    *int `json:"next_page"`
	TotalPages  int  `json:"total_pages"`
	TotalCount  int  `json:"total_count"`
	// contains filtered or unexported fields
}

type PaginateOpts

type PaginateOpts struct {
	PageNumber  int
	AmountItems int
	Query       bson.M
	SortOrder   string
}

type Service

type Service interface {
	Paginate(ctx context.Context, collection string, result interface{}, opts PaginateOpts) (Meta, error)
}

func NewPaginationService

func NewPaginationService(opts ServiceOpts) Service

type ServiceOpts

type ServiceOpts struct {
	PerPageDefault int
	MaxPerPage     int
}

func (ServiceOpts) Paginate

func (s ServiceOpts) Paginate(ctx context.Context,
	collection string,
	result interface{},
	opts PaginateOpts) (Meta, error)

Jump to

Keyboard shortcuts

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