From c4a4a8b5f60a568abd2af614ca4a5d06855bc3a1 Mon Sep 17 00:00:00 2001 From: xengineering Date: Sun, 7 Apr 2024 10:42:03 +0200 Subject: model: Add helper function for safe CRUD This removes the redundant setup of a database/sql.Tx in each HTTP handler. --- model/object.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'model/object.go') diff --git a/model/object.go b/model/object.go index 63ef419..bcbba3e 100644 --- a/model/object.go +++ b/model/object.go @@ -10,3 +10,18 @@ type Object interface { Update(tx *sql.Tx) error Delete(tx *sql.Tx) error } + +func SafeCrud(crud func(tx *sql.Tx) error) error { + tx, err := NewTx() + if err != nil { + return err + } + + err = crud(tx) + if err != nil { + Rollback(tx) + return err + } + + return tx.Commit() +} -- cgit v1.2.3-70-g09d2