Add custom pagination template

This commit is contained in:
Achim Rohn
2025-09-12 01:54:21 +02:00
parent 941aea49a8
commit cd1d85b1a9
4 changed files with 114 additions and 33 deletions
+3 -32
View File
@@ -3,11 +3,9 @@ package main
import (
"context"
"ersteller-lib/schema/ent/example/ent"
"ersteller-lib/schema/ent/example/ent/user"
"log"
"time"
"entgo.io/ent/dialect/sql"
_ "github.com/mattn/go-sqlite3"
)
@@ -40,7 +38,8 @@ func main() {
// log.Fatalf("failed updating user: %w", err)
//}j
//log.Println("user was updated", u)
users, nextId, hasNext, err := ListUsersAfterID(ctx, client, 0, 2)
query := client.User.Query()
users, nextId, hasNext, err := query.PaginateAfterID(ctx, 0, 2)
if err != nil {
log.Fatalf("failed listing users: %w", err)
}
@@ -50,7 +49,7 @@ func main() {
log.Println("user", u.ID, u.Email, u.Password)
}
}
users, nextId, hasNext, err = ListUsersAfterID(ctx, client, nextId, 2)
users, nextId, hasNext, err = query.PaginateAfterID(ctx, nextId, 2)
if err != nil {
log.Fatalf("failed listing users: %w", err)
}
@@ -62,31 +61,3 @@ func main() {
}
}
// afterID is the last ID from the previous page. Use 0 for the first page.
func ListUsersAfterID(ctx context.Context, client *ent.Client, afterID, limit int) ([]*ent.User, int, bool, error) {
q := client.User.Query().
Order(user.ByID(sql.OrderAsc())).
Limit(limit + 1) // fetch one extra to detect "has next"
if afterID > 0 {
q = q.Where(user.IDGT(afterID))
}
rows, err := q.All(ctx)
if err != nil {
return nil, -1, false, err
}
hasNext := len(rows) > limit
if hasNext {
rows = rows[:limit]
}
var next int
if len(rows) > 0 {
last := rows[len(rows)-1].ID
next = last
}
return rows, next, hasNext, nil
}