31 lines
734 B
Go
31 lines
734 B
Go
// Copyright (C) 2024 Mya Pitzeruse
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package crud
|
|
|
|
import (
|
|
"context"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// UpdateFunc defines a signature that is used by Updater to return a function that can update data in the database.
|
|
type UpdateFunc[T any] func(ctx context.Context, patch T, filters ...map[string]interface{}) error
|
|
|
|
// Updater returns a function used to update information in the database.
|
|
func Updater[T any](db *gorm.DB) UpdateFunc[T] {
|
|
prototype := new(T)
|
|
|
|
return func(ctx context.Context, patch T, filters ...map[string]interface{}) error {
|
|
q := Transaction(ctx, db).
|
|
Model(prototype).
|
|
Limit(1)
|
|
|
|
for _, filter := range filters {
|
|
q = q.Where(filter)
|
|
}
|
|
|
|
return q.Updates(patch).Error
|
|
}
|
|
}
|