2023-09-06 22:20:09 +01:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2024-05-31 14:57:54 +01:00
|
|
|
"errors"
|
2023-09-06 22:20:09 +01:00
|
|
|
"github.com/1f349/tulip/database"
|
2024-05-13 20:06:17 +01:00
|
|
|
"github.com/1f349/tulip/logger"
|
2023-09-06 22:20:09 +01:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2024-05-31 14:57:54 +01:00
|
|
|
var ErrDatabaseActionFailed = errors.New("database action failed")
|
|
|
|
|
2023-09-07 11:45:16 +01: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 14:57:54 +01:00
|
|
|
func (h *HttpServer) DbTx(rw http.ResponseWriter, action func(tx *database.Queries) error) bool {
|
|
|
|
logger.Logger.Helper()
|
|
|
|
if h.DbTxError(action) != nil {
|
2023-09-06 22:20:09 +01:00
|
|
|
http.Error(rw, "Database error", http.StatusInternalServerError)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
2024-05-31 14:57:54 +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
|
|
|
|
}
|