1
gorm-crud/getter.go
2024-01-28 15:19:39 -06:00

38 lines
807 B
Go

// Copyright (C) 2024 Mya Pitzeruse
// SPDX-License-Identifier: MIT
package crud
import (
"context"
"gorm.io/gorm"
)
// GetFunc defines the signature of the function returned by Getter. It streamlines the process of reading single
// records from the database.
type GetFunc[T any] func(ctx context.Context, filters ...map[string]interface{}) (*T, error)
// Getter returns a function that can read data from a gorm database.
func Getter[T any](db *gorm.DB) GetFunc[T] {
prototype := new(T)
return func(ctx context.Context, filters ...map[string]interface{}) (*T, error) {
q := Transaction(ctx, db).
Model(prototype)
for _, filter := range filters {
q = q.Where(filter)
}
body := new(T)
err := q.First(body).Error
if err != nil {
return nil, err
}
return body, nil
}
}