lavender/server/db.go

45 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-02-07 01:18:17 +00:00
package server
import (
"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-10-06 15:50:23 +01:00
var _ error = (*ErrDatabaseActionFailed)(nil)
type ErrDatabaseActionFailed struct {
err error
}
func (e ErrDatabaseActionFailed) Error() string {
return "database action failed: " + e.err.Error()
}
func (e ErrDatabaseActionFailed) Unwrap() error {
return e.err
}
2024-05-31 13:51:44 +01:00
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-09-13 15:31:40 +01:00
func (h *httpServer) DbTx(rw http.ResponseWriter, action func(tx *database.Queries) error) bool {
2024-05-31 13:51:44 +01:00
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
2024-09-13 15:31:40 +01:00
func (h *httpServer) DbTxError(action func(tx *database.Queries) error) error {
2024-05-31 13:51:44 +01:00
logger.Logger.Helper()
err := action(h.db)
if err != nil {
logger.Logger.Warn("Database action error", "err", err)
2024-10-06 15:50:23 +01:00
return ErrDatabaseActionFailed{err: err}
2024-05-31 13:51:44 +01:00
}
return nil
}