-
Notifications
You must be signed in to change notification settings - Fork 0
/
fixtures.go
98 lines (85 loc) · 2.05 KB
/
fixtures.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
90
91
92
93
94
95
96
97
98
package fixures
import (
"context"
"embed"
"encoding/json"
"fmt"
"log/slog"
"time"
"github.com/aziemski/bookstore/internal/core"
"github.com/aziemski/bookstore/internal/x/xlog"
)
//go:embed assets/fake_data.json
var fakeDataDir embed.FS
type (
FakeData struct {
LoremIpsum string `json:"lorem_ipsum"`
Books []FakeBook `json:"books"`
}
FakeBook struct {
Title string `json:"title"`
Author string `json:"author"`
Summary string `json:"summary"`
ImageLink string `json:"image_link"`
Category string `json:"category"`
Featured bool `json:"featured"`
}
)
func Populate(repo *core.Repository, log *slog.Logger) {
try := func() error {
if c, err := repo.GetTotalCount(context.Background()); c > 0 && err == nil {
log.Info("book records found ", "count", c)
return nil
}
time.Sleep(3 * time.Second)
fd := readFakeData(log)
for i, fb := range fd.Books {
log.Info("inserting book")
_, err := repo.InsertNew(context.Background(), &core.Book{
ID: fmt.Sprintf("b%d", i),
Title: fb.Title,
Author: fb.Author,
Summary: fb.Summary,
Description: fd.LoremIpsum,
ImageLink: fb.ImageLink,
Category: fb.Category,
Featured: fb.Featured,
})
if err != nil {
log.Warn("cannot save book", xlog.Err(err))
return err
}
}
return nil
}
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
defer cancel()
for {
select {
case <-ctx.Done():
log.Warn("received cancellation signal due to deadline.")
return
default:
if err := try(); err == nil {
return
}
}
}
}
func readFakeData(log *slog.Logger) FakeData {
result := FakeData{}
file, err := fakeDataDir.Open("assets/fake_data.json")
if err != nil {
log.Error("unexpected os.Open() err", xlog.Err(err))
return result
}
defer func() {
_ = file.Close()
}()
decoder := json.NewDecoder(file)
if err = decoder.Decode(&result); err != nil {
log.Error("unexpected decoder.Decode() err", xlog.Err(err))
return result
}
return result
}