Scope function for GORM queries provides easy filtering with query parameters
go get github.com/ActiveChooN/gin-gorm-filter
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
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
curl -X GET http://localhost:8080/users?page=1&limit=10&order_by=username&order_direction=asc&filter="name:John"
filter=username:John
matches only when the username is exactly John
filter=age>35
matches only when age is more than 35filter=salary<80000
matches only when salary is less than 80,000filter=items>=100
matches only when items is at least 100filter=score<=100000
matches when score is 100,000 or lowerstate!=FAIL
matches when state has any value other than FAILfilter=lastName~illi
matches when lastName contains the substring illi