/
update.go
37 lines (29 loc) · 802 Bytes
/
update.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package todos
import (
"context"
"github.com/Fs02/go-todo-backend/scores"
"github.com/go-rel/rel"
"go.uber.org/zap"
)
type update struct {
repository rel.Repository
scores scores.Service
}
func (u update) Update(ctx context.Context, todo *Todo, changes rel.Changeset) error {
if err := todo.Validate(); err != nil {
logger.Warn("validation error", zap.Error(err))
return err
}
// update score if completed is changed.
if changes.FieldChanged("completed") {
return u.repository.Transaction(ctx, func(ctx context.Context) error {
u.repository.MustUpdate(ctx, todo, changes)
if todo.Completed {
return u.scores.Earn(ctx, "todo completed", 1)
}
return u.scores.Earn(ctx, "todo uncompleted", -2)
})
}
u.repository.MustUpdate(ctx, todo, changes)
return nil
}