-
Notifications
You must be signed in to change notification settings - Fork 1
/
get.go
82 lines (69 loc) · 1.85 KB
/
get.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
package get
import (
"context"
"errors"
"github.com/PacktPublishing/Hands-On-Dependency-Injection-in-Go/ch12/acme/internal/logging"
"github.com/PacktPublishing/Hands-On-Dependency-Injection-in-Go/ch12/acme/internal/modules/data"
)
var (
// error thrown when the requested person is not in the database
errPersonNotFound = errors.New("person not found")
)
// NewGetter creates and initializes a Getter
func NewGetter(cfg Config) *Getter {
return &Getter{
cfg: cfg,
}
}
// Config is the configuration for Getter
type Config interface {
Logger() logging.Logger
DataDSN() string
}
// Getter will attempt to load a person.
// It can return an error caused by the data layer or when the requested person is not found
type Getter struct {
cfg Config
data myLoader
}
// Do will perform the get
func (g *Getter) Do(ID int) (*Person, error) {
// load person from the data layer
person, err := g.getLoader().Load(context.TODO(), ID)
if err != nil {
if err == data.ErrNotFound {
// By converting the error we are hiding the implementation details from our users.
return nil, errPersonNotFound
}
return nil, err
}
return g.convert(person), err
}
func (g *Getter) getLoader() myLoader {
if g.data == nil {
g.data = data.NewDAO(g.cfg)
}
return g.data
}
func (g *Getter) convert(in *data.Person) *Person {
return &Person{
ID: in.ID,
Currency: in.Currency,
FullName: in.FullName,
Phone: in.Phone,
Price: in.Price,
}
}
//go:generate mockery -name=myLoader -case underscore -testonly -inpkg -note @generated
type myLoader interface {
Load(ctx context.Context, ID int) (*data.Person, error)
}
// Person is a copy/sub-set of data.Person so that the relationship does not leak.
// It also allows us to remove/hide and internal fields
type Person struct {
ID int
FullName string
Phone string
Currency string
Price float64
}