filter

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2024 License: MIT Imports: 7 Imported by: 0

README

Gin GORM filter

GitHub GitHub Workflow Status (branch) GitHub release (latest by date)

Scope function for GORM queries provides easy filtering with query parameters

Usage

go get github.com/ActiveChooN/gin-gorm-filter

Model definition

type UserModel struct {
    gorm.Model
    Username string `gorm:"uniqueIndex" filter:"param:login;searchable;filterable"`
    FullName string `filter:"searchable"`
    Role     string `filter:"filterable"`
}

param tag in that case defines custom column name for the query param

Controller Example

func GetUsers(c *gin.Context) {
	var users []UserModel
	var usersCount int64
	db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
	err := db.Model(&UserModel{}).Scopes(
		filter.FilterByQuery(c, filter.ALL),
	).Count(&usersCount).Find(&users).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, err.Error())
		return
	}
	serializer := serializers.PaginatedUsers{Users: users, Count: usersCount}
	c.JSON(http.StatusOK, serializer.Response())
}

Any filter combination can be used here filter.PAGINATION|filter.ORDER_BY e.g. Important note: GORM model should be initialize first for DB, otherwise filter and search won't work

Request example

curl -X GET http://localhost:8080/users?page=1&limit=10&order_by=username&order_direction=asc&filter="name:John"

Supported filter operators

  • : The equality operator filter=username:John matches only when the username is exactly John
  • > The greater than operator filter=age>35 matches only when age is more than 35
  • < The less than operator filter=salary<80000 matches only when salary is less than 80,000
  • >= The greater than or equals to operator filter=items>=100 matches only when items is at least 100
  • <= The less than or equals to operator filter=score<=100000 matches when score is 100,000 or lower
  • != The not equals to operator state!=FAIL matches when state has any value other than FAIL
  • ~ The like operator filter=lastName~illi matches when lastName contains the substring illi

TODO list

  • Write tests for the lib with CI integration
  • Add support for case-insensitive search
  • Add other filters, like > or !=
  • Add support for multiple filters in one query
  • Add suport for filtering for related models

Documentation

Index

Constants

View Source
const (
	SEARCH   = 1  // Filter response with LIKE query "search={search_phrase}"
	FILTER   = 2  // Filter response by column name values "filter={column_name}:{value}"
	PAGINATE = 4  // Paginate response with page and page_size
	ORDER_BY = 8  // Order response by column name
	ALL      = 15 // Equivalent to SEARCH|FILTER|PAGINATE|ORDER_BY

)

Variables

This section is empty.

Functions

func FilterByQuery

func FilterByQuery(c *gin.Context, config int) func(db *gorm.DB) *gorm.DB

Filter DB request with query parameters. Note: Don't forget to initialize DB Model first, otherwise filter and search won't work Example:

db.Model(&UserModel).Scope(filter.FilterByQuery(ctx, filter.ALL)).Find(&users)

Or if only pagination and order is needed:

db.Model(&UserModel).Scope(filter.FilterByQuery(ctx, filter.PAGINATION|filter.ORDER_BY)).Find(&users)

And models should have appropriate`filter` tags:

type User struct {
	gorm.Model
	Username string `gorm:"uniqueIndex" filter:"param:login;searchable;filterable"`
	// `param` defines custom column name for the query param
	FullName string `filter:"searchable"`
}

Types

This section is empty.

Jump to

Keyboard shortcuts

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