40 lines
924 B
Go
40 lines
924 B
Go
// Copyright (C) 2024 Mya Pitzeruse
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package crud
|
|
|
|
import (
|
|
"context"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// ListFunc defines a function signature used to list data from the underlying gorm database. It ensures that size and
|
|
// scoping of queries is taken into consideration.
|
|
type ListFunc[T any] func(ctx context.Context, offset, count int, filters ...map[string]interface{}) ([]T, error)
|
|
|
|
// Lister returns a ListFunc to be used to list data from gorm.
|
|
func Lister[T any](db *gorm.DB) ListFunc[T] {
|
|
prototype := new(T)
|
|
|
|
return func(ctx context.Context, offset, count int, filters ...map[string]interface{}) ([]T, error) {
|
|
q := Transaction(ctx, db).
|
|
Model(prototype).
|
|
Offset(offset).
|
|
Limit(count)
|
|
|
|
for _, filter := range filters {
|
|
q = q.Where(filter)
|
|
}
|
|
|
|
result := make([]T, 0, count)
|
|
|
|
err := q.Find(&result).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
}
|