69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package utils
|
|
|
|
import (
|
|
"errors"
|
|
"strconv"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
type OffsetPaginationError struct {
|
|
Page int
|
|
Pages int
|
|
NextPage int
|
|
LastPage int
|
|
}
|
|
|
|
func (p *OffsetPaginationError) Error() string {
|
|
return "Not an error, just for offsetbased pagination."
|
|
}
|
|
|
|
func NewOffsetPaginationError(page int, pages int) error {
|
|
var nextPage int
|
|
if page+1 <= pages {
|
|
nextPage = page + 1
|
|
} else {
|
|
nextPage = -1
|
|
}
|
|
|
|
return &OffsetPaginationError{Page: page, Pages: pages, NextPage: nextPage, LastPage: page - 1}
|
|
}
|
|
|
|
type KeysetPaginationError struct {
|
|
Key int
|
|
NextKey int
|
|
PreviousKey int
|
|
}
|
|
|
|
func (p *KeysetPaginationError) Error() string {
|
|
return "Not an error, just for Keysetbased pagination."
|
|
}
|
|
|
|
func NewKeysetPaginationError(key int, next int, previous int) error {
|
|
return &KeysetPaginationError{Key: key, NextKey: next, PreviousKey: previous}
|
|
}
|
|
|
|
func AddPaginationParams(c *fiber.Ctx) error {
|
|
err := c.Next()
|
|
if err != nil {
|
|
|
|
var offset *OffsetPaginationError
|
|
if errors.As(err, &offset) {
|
|
c.Append("X-Page", strconv.Itoa(offset.Page))
|
|
c.Append("X-Pages", strconv.Itoa(offset.Pages))
|
|
c.Append("X-Next-Page", strconv.Itoa(offset.NextPage))
|
|
c.Append("X-Last-Page", strconv.Itoa(offset.LastPage))
|
|
return nil
|
|
}
|
|
|
|
var keyset *KeysetPaginationError
|
|
if errors.As(err, &keyset) {
|
|
c.Append("X-Key", strconv.Itoa(keyset.Key))
|
|
c.Append("X-Previous-Key", strconv.Itoa(keyset.PreviousKey))
|
|
c.Append("X-Next-Key", strconv.Itoa(keyset.NextKey))
|
|
return nil
|
|
}
|
|
}
|
|
return err
|
|
}
|