-
Notifications
You must be signed in to change notification settings - Fork 0
/
uow.go
89 lines (70 loc) · 1.9 KB
/
uow.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package create_invoice
import (
"context"
"errors"
"github.com/devdammit/shekel/cmd/unit/internal/entities"
"github.com/devdammit/shekel/internal/resources"
"go.etcd.io/bbolt"
)
type invoicesRepository interface {
CreateTx(tx *bbolt.Tx, invoice entities.Invoice) (*entities.Invoice, error)
}
type templatesRepository interface {
CreateTx(tx *bbolt.Tx, template entities.InvoiceTemplate) (*entities.InvoiceTemplate, error)
}
type Repositories struct {
invoices invoicesRepository
templates templatesRepository
}
type CreateInvoiceUoW struct {
db *resources.Bolt
invoices []entities.Invoice
template *entities.InvoiceTemplate
repositories Repositories
}
func NewUoW(db *resources.Bolt, repository invoicesRepository, templatesRepository templatesRepository) *CreateInvoiceUoW {
return &CreateInvoiceUoW{
db: db,
invoices: make([]entities.Invoice, 0),
repositories: Repositories{
invoices: repository,
templates: templatesRepository,
},
}
}
func (u *CreateInvoiceUoW) CreateInvoices(invoices []entities.Invoice, template entities.InvoiceTemplate) {
u.template = &template
u.invoices = invoices
}
func (u *CreateInvoiceUoW) CreateInvoice(invoice entities.Invoice) {
u.invoices = append(u.invoices, invoice)
}
func (u *CreateInvoiceUoW) Commit(ctx context.Context) error {
if u.invoices == nil {
return errors.New("missing data")
}
return u.db.Update(func(tx *bbolt.Tx) error {
if len(u.invoices) == 1 {
_, err := u.repositories.invoices.CreateTx(tx, u.invoices[0])
if err != nil {
return err
}
return nil
}
if u.template == nil {
return errors.New("missing data")
}
template, err := u.repositories.templates.CreateTx(tx, *u.template)
if err != nil {
return err
}
for _, invoice := range u.invoices {
invoice.Template = template
_, err = u.repositories.invoices.CreateTx(tx, invoice)
if err != nil {
return err
}
}
return nil
})
}