Skip to content

Commit

Permalink
add paginate for db (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
huweihuang authored Jun 24, 2024
1 parent 43dc08e commit 055afa6
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 2 deletions.
16 changes: 16 additions & 0 deletions config/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# config

`config` encapsulates the use of `viper` and parses the configuration file of the specified path into a structure.

```go
import(
"github.com/huweihuang/golib/config"
)

func main() {
err := config.InitConfigObjectByPath(configFile, &configs.GlobalConfig)
if err != nil {
panic(err)
}
}
```
43 changes: 43 additions & 0 deletions db/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package db

import "gorm.io/gorm"

func Paginate(page int, pageSize int) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if page == 0 {
page = 1
}
switch {
case pageSize > 500:
pageSize = 500
case pageSize <= 0:
pageSize = 10
}
offset := (page - 1) * pageSize
return db.Offset(offset).Limit(pageSize)
}
}

func PaginatedFind(db *gorm.DB, page, pageSize int, target interface{}) (count int64, err error) {
err = db.Count(&count).Error
if err != nil {
return 0, err
}
err = db.Scopes(Paginate(page, pageSize)).Find(target).Error
return count, err
}

func ParamsToQuery(queryMap map[string]interface{}) (queryStr string, args []interface{}) {
for key, value := range queryMap {
queryStr = AppendQuery(queryStr, key)
args = append(args, value)
}
return queryStr, args
}

func AppendQuery(query, newQuery string) string {
if query != "" {
return query + " AND " + newQuery
}
return newQuery
}
1 change: 0 additions & 1 deletion gin/middlewares/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ func SucceedWrapper(c *gin.Context, msg string, data interface{}) {
Message: fmt.Sprintf("%s succeed", msg),
Data: data,
}
log.Logger().With("resp", resp).Info(msg)
c.JSON(http.StatusOK, resp)
}

Expand Down
2 changes: 1 addition & 1 deletion httplib/httplib.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
log "github.com/huweihuang/golib/logger/zap"
)

func CallURL(method, url, path string, header map[string]string, request interface{}, response interface{}) (
func RequestURL(method, url, path string, header map[string]string, request interface{}, response interface{}) (
statusCode int, body []byte, err error) {

log.Logger().With(
Expand Down

0 comments on commit 055afa6

Please sign in to comment.