metakit

package module
v0.5.11 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2024 License: MIT Imports: 4 Imported by: 0

README

Pagination-Metakit

Pagination-Metakit is a Go package designed to simplify pagination and sorting functionalities for applications using GORM (Go Object-Relational Mapping) and Pure SQL. This package provides a Metadata structure to manage pagination and sorting parameters, and a GORM scope function to apply these settings to database queries, but not for only GORM, Pagination-Metakit also support pure sql pagination.

Overview

  • Pagination: Easily handle pagination with customizable page size.
  • Default Settings: Provides sensible defaults for page, page size, and sort direction.
  • Dual Functionality: Supports both GORM and pure SQL pagination.

Installation

To install the package, use go get:

go get github.com/Nicolas-ggd/paginate-metakit

Usage

Metadata Structure

The Metadata structure holds the pagination and sorting parameters:

type Metadata struct {
    Page          int    `form:"page" json:"page"`
    PageSize      int    `form:"page_size" json:"page_size"`
    Sort          string `form:"sort" json:"sort"`
    SortDirection string `form:"sort_direction" json:"sort_direction"`
    TotalRows     int64  `json:"total_rows"`
    TotalPages    int64  `json:"total_pages"`
}

Example Usage of GPaginate function

package main

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"fmt"
	"github.com/Nicolas-ggd/paginate-metakit"
	"net/http"
)

func main() {
	r.GET("/items", func(c *gin.Context) {
		var metadata metakit.Metadata

		// Bind metakit Metadata struct 
		err := c.ShouldBind(&metadata)
		if err != nil {
			c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err})
			return
		}

		// Count total rows
		var totalRows int64
		db.Model(&YourModel{}).Count(&totalRows)
		metadata.TotalRows = totalRows

		// Fetch paginated and sorted results
		var results []YourModel
		db.Scopes(metakit.GormPaginate(&metadata)).Find(&results)

		c.JSON(http.StatusOK, gin.H{"metadata": metadata, "results": results})
	})

	r.Run()
}

Example usage of SQLPaginate function

package main

import (
    "database/sql"
    "log"
    "net/http"
    "github.com/gin-gonic/gin"
    "github.com/Nicolas-ggd/paginate-metakit"
    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "user=youruser dbname=yourdb sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    r := gin.Default()
    
    r.GET("/items", func(c *gin.Context) {
        var metadata metakit.Metadata
        
        // Bind metakit Metadata struct
        err := c.ShouldBind(&metadata)
        if err != nil {
            c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err})
            return
        }
        
        // Count total rows
        row := db.QueryRow("SELECT COUNT(*) FROM your_table")
        err = row.Scan(&metadata.TotalRows)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err})
            return
        }

        // Fetch paginated and sorted results
        query := "SELECT * FROM your_table"
        rows, err := metakit.QueryContextPaginate(context.Background(), db, 1, query, &metadata)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err})
            return
        }
        defer rows.Close()

        var results []YourModel
        for rows.Next() {
            var item YourModel
            // Scan your results here
            results = append(results, item)
        }
        
        c.JSON(http.StatusOK, gin.H{"metadata": metadata, "results": results})
    })

    r.Run()
}

Contributing

This project is licensed under the MIT License. See the LICENSE file for details.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GPaginate added in v0.5.7

func GPaginate(m *Metadata) func(db *gorm.DB) *gorm.DB

GPaginate is GORM scope function. Paginate calculates the total pages and offset based on current metadata and applies pagination to the Gorm query GPaginate function cares Page and PageSize automatically, you can use your own function to replace it, it just overwrite fields

func QueryContextPaginate added in v0.5.11

func QueryContextPaginate(ctx context.Context, db *sql.DB, dialect Dialect, query string, m *Metadata, args ...any) (*sql.Rows, error)

QueryContextPaginate calculates the total pages and offset based on the current metadata and applies pagination to the SQL query

Types

type Dialect added in v0.5.11

type Dialect int
const (
	MySQL Dialect = iota
	PostgreSQL
	SQLite
)

type Metadata

type Metadata struct {
	// Page represents current page
	Page int `form:"page" json:"page"`

	// PageSize is capacity of per page items
	PageSize int `form:"page_size" json:"page_size"`

	// Sort is string type which defines the sort type of data
	Sort string `form:"sort" json:"sort"`

	// SortDirection defines sorted column name
	SortDirection string `form:"sort_direction" json:"sort_direction"`

	// TotalRows defines the quantity of total rows
	TotalRows int64 `json:"total_rows"`

	// TotalPages defines the quantity of total pages, it's defined based on page size and total rows
	TotalPages int64 `json:"total_pages"`
}

func (*Metadata) SortDirectionParams

func (m *Metadata) SortDirectionParams()

SortDirectionParams function check SortDirection parameter, if it's empty, then it sets ascending order by default

func (*Metadata) SortParams

func (m *Metadata) SortParams(sort string)

SortParams function take string parameter of sort and set of Sort value

Jump to

Keyboard shortcuts

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