/
main.go
73 lines (65 loc) · 1.71 KB
/
main.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
package seed
import (
"context"
"database/sql"
"errors"
"time"
"github.com/1995parham-teaching/tinyurl/internal/domain/model/url"
"github.com/1995parham-teaching/tinyurl/internal/domain/repository/urlrepo"
"github.com/1995parham-teaching/tinyurl/internal/infra/config"
"github.com/1995parham-teaching/tinyurl/internal/infra/db"
"github.com/1995parham-teaching/tinyurl/internal/infra/logger"
"github.com/1995parham-teaching/tinyurl/internal/infra/repository"
"github.com/1995parham-teaching/tinyurl/internal/infra/telemetry"
"github.com/spf13/cobra"
"go.uber.org/fx"
"go.uber.org/zap"
)
func main(logger *zap.Logger, repo urlrepo.Repository, shutdowner fx.Shutdowner) {
ctx := context.Background()
records := []url.URL{
{
Key: "static_google",
URL: "https://google.com",
Visits: 0,
Expire: sql.NullTime{
Time: time.Now(),
Valid: false,
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
}
for _, record := range records {
if err := repo.Create(ctx, record); err != nil {
if errors.Is(err, urlrepo.ErrDuplicateShortURL) {
continue
}
logger.Fatal("cannot create record", zap.Error(err))
}
}
_ = shutdowner.Shutdown()
}
// Register seed command.
func Register(root *cobra.Command) {
root.AddCommand(
//nolint: exhaustruct
&cobra.Command{
Use: "seed",
Short: "Add sample records into database",
Run: func(_ *cobra.Command, _ []string) {
fx.New(
fx.Provide(config.Provide),
fx.Provide(logger.Provide),
fx.Provide(db.Provide),
fx.Provide(telemetry.ProvideNull),
fx.Provide(
fx.Annotate(repository.ProvideURLDB, fx.As(new(urlrepo.Repository))),
),
fx.NopLogger,
fx.Invoke(main),
).Run()
},
},
)
}