Pagination
This guide discusses pagination in Go, specifically on how to implement pagination in the UserController and userService.
Structs and Methods
The pagination process uses several structs and methods:
GetPageOptions()
method: Retrieves the PageOptions.
go
GetPageOptions() *PageOptions
GetPageOptionsWithOptions(options *PageOptionsOptions)
method: Retrieves the PageOptions with options specified.
go
GetPageOptionsWithOptions(options *PageOptionsOptions) *PageOptions
PageOptionsOptions
struct: Defines allowed orderings.
go
type PageOptionsOptions struct {
OrderByAllowed []string
}
Pagination(c core.IHTTPContext)
method: This function handles pagination. It creates a new UserService and calls its Pagination method, returning the JSON representation of the response.
go
func (m UserController) Pagination(c core.IHTTPContext) error {
userSvc := services.NewUserService(c)
res, ierr := userSvc.Pagination(c.GetPageOptions())
if ierr != nil {
return c.JSON(ierr.GetStatus(), ierr.JSON())
}
return c.JSON(http.StatusOK, res)
}
Pagination(pageOptions *core.PageOptions)
method: This function handles the logic for user pagination.
go
func (s userService) Pagination(pageOptions *core.PageOptions) (*repository.Pagination[models.User], core.IError) {
// Implementation for user pagination
return repo.User(s.ctx, repo.UserOrderBy(pageOptions)).Pagination(pageOptions) // Calling the Pagination method of the repo.User repository
}
Pagination[M any]
struct: The generic struct representing the Pagination result. It includes the page, total, limit, count, and items.
go
type Pagination[M any] struct {
Page int64 `json:"page" example:"1"`
Total int64 `json:"total" example:"45"`
Limit int64 `json:"limit" example:"30"`
Count int64 `json:"count" example:"30"`
Items []M `json:"items"`
}
Flow of Pagination
- When a pagination request comes in, it is handled by the
Pagination(c core.IHTTPContext)
method of theUserController
. - A new
userService
is instantiated viaservices.NewUserService(c)
. - The
Pagination(c.GetPageOptions())
method of theuserService
is called with thePageOptions
fetched from the context. - Within the
userService
pagination method, therepo.User(s.ctx, repo.UserOrderBy(pageOptions)).Pagination(pageOptions)
call is made. It is responsible for actual data retrieval and pagination. - The Pagination method of the
User
repository returns the paginated data based on the options passed. - If an error occurs during the process, it is caught and returned in a JSON response. If the process is successful, the data is returned in a JSON response with the HTTP status 200.
Conclusion
The above code and guide demonstrate how to perform pagination in Go. Remember to adjust the implementation according to the specifics of your database or data source.