-
Notifications
You must be signed in to change notification settings - Fork 62
/
get.go
62 lines (51 loc) · 1.42 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
package get
import (
"context"
"errors"
"github.com/PacktPublishing/Hands-On-Dependency-Injection-in-Go/ch09/acme/internal/logging"
"github.com/PacktPublishing/Hands-On-Dependency-Injection-in-Go/ch09/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) (*data.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 person, err
}
func (g *Getter) getLoader() myLoader {
if g.data == nil {
g.data = data.NewDAO(g.cfg)
}
return g.data
}
//go:generate mockery -name=myLoader -case underscore -testonly -inpkg -note @generated
type myLoader interface {
Load(ctx context.Context, ID int) (*data.Person, error)
}