lavender/server/db.go

34 lines
930 B
Go
Raw Normal View History

2024-02-07 01:18:17 +00:00
package server
import (
2024-05-31 13:51:44 +01:00
"errors"
2024-02-07 01:18:17 +00:00
"github.com/1f349/lavender/database"
2024-05-13 20:33:25 +01:00
"github.com/1f349/lavender/logger"
2024-02-07 01:18:17 +00:00
"net/http"
)
2024-05-31 13:51:44 +01:00
var ErrDatabaseActionFailed = errors.New("database action failed")
2024-02-07 01:18:17 +00:00
// DbTx wraps a database transaction with http error messages and a simple action
// function. If the action function returns an error the transaction will be
// rolled back. If there is no error then the transaction is committed.
2024-05-31 13:51:44 +01:00
func (h *HttpServer) DbTx(rw http.ResponseWriter, action func(tx *database.Queries) error) bool {
logger.Logger.Helper()
if h.DbTxError(action) != nil {
2024-02-07 01:18:17 +00:00
http.Error(rw, "Database error", http.StatusInternalServerError)
return true
}
return false
}
2024-05-31 13:51:44 +01:00
func (h *HttpServer) DbTxError(action func(tx *database.Queries) error) error {
logger.Logger.Helper()
err := action(h.db)
if err != nil {
logger.Logger.Warn("Database action error", "err", err)
return ErrDatabaseActionFailed
}
return nil
}