generated from mikestefanello/pagoda
/
container.go
228 lines (180 loc) · 5.44 KB
/
container.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package services
import (
"context"
"database/sql"
"errors"
"fmt"
// Required by ent
"github.com/jackc/pgconn"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
"github.com/francoganga/pagoda_bun/cmd/web/migrations"
"github.com/francoganga/pagoda_bun/config"
// Require by ent
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/migrate"
"github.com/uptrace/bun/extra/bundebug"
)
// Container contains all services used by the application and provides an easy way to handle dependency
// injection including within tests
type Container struct {
// Validator stores a validator
Validator *Validator
// Web stores the web framework
Web *echo.Echo
// Config stores the application configuration
Config *config.Config
// Cache contains the cache client
Cache *CacheClient
// Database stores the connection to the database
Database *sql.DB
// Bun DB connection
Bun *bun.DB
// Mail stores an email sending client
Mail *MailClient
// Auth stores an authentication client
Auth *AuthClient
// TemplateRenderer stores a service to easily render and cache templates
TemplateRenderer *TemplateRenderer
// Tasks stores the task client
Tasks *TaskClient
}
// NewContainer creates and initializes a new Container
func NewContainer() *Container {
c := new(Container)
c.initConfig()
c.initValidator()
c.initWeb()
c.initCache()
c.initDatabase()
c.initAuth()
c.initTemplateRenderer()
c.initMail()
c.initTasks()
return c
}
// Shutdown shuts the Container down and disconnects all connections
func (c *Container) Shutdown() error {
if err := c.Tasks.Close(); err != nil {
return err
}
if err := c.Cache.Close(); err != nil {
return err
}
if err := c.Database.Close(); err != nil {
return err
}
return nil
}
// initConfig initializes configuration
func (c *Container) initConfig() {
cfg, err := config.GetConfig()
if err != nil {
panic(fmt.Sprintf("failed to load config: %v", err))
}
c.Config = &cfg
}
// initValidator initializes the validator
func (c *Container) initValidator() {
c.Validator = NewValidator()
}
// initWeb initializes the web framework
func (c *Container) initWeb() {
c.Web = echo.New()
// Configure logging
switch c.Config.App.Environment {
case config.EnvProduction:
c.Web.Logger.SetLevel(log.WARN)
default:
c.Web.Logger.SetLevel(log.DEBUG)
}
c.Web.Validator = c.Validator
}
// initCache initializes the cache
func (c *Container) initCache() {
var err error
if c.Cache, err = NewCacheClient(c.Config); err != nil {
panic(err)
}
}
// initDatabase initializes the database
// If the environment is set to test, the test database will be used and will be dropped, recreated and migrated
func (c *Container) initDatabase() {
var err error
getAddr := func(dbName string) string {
return fmt.Sprintf("postgresql://%s:%s@%s:%d/%s",
c.Config.Database.User,
c.Config.Database.Password,
c.Config.Database.Hostname,
c.Config.Database.Port,
dbName,
)
}
c.Database, err = sql.Open("pgx", getAddr(c.Config.Database.Database))
if err != nil {
panic(fmt.Sprintf("failed to connect to database: %v", err))
}
c.Bun = bun.NewDB(c.Database, pgdialect.New())
c.Bun.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true), bundebug.FromEnv("BUNDEBUG")))
// Check if this is a test environment
if c.Config.App.Environment == config.EnvTest {
// Drop the test database, ignoring errors in case it doesn't yet exist
_, _ = c.Database.Exec("DROP DATABASE " + c.Config.Database.TestDatabase)
// Create the test database
if _, err = c.Database.Exec("CREATE DATABASE " + c.Config.Database.TestDatabase); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
fmt.Println(pgErr.Message) // => syntax error at end of input
fmt.Println(pgErr.Code) // => 42601
if pgErr.Code != "42P04" {
panic(fmt.Sprintf("failed to create test database: %v", err))
}
}
}
// Connect to the test database
if err = c.Database.Close(); err != nil {
panic(fmt.Sprintf("failed to close database connection: %v", err))
}
c.Database, err = sql.Open("pgx", getAddr(c.Config.Database.TestDatabase))
if err != nil {
panic(fmt.Sprintf("failed to connect to database: %v", err))
}
c.Bun = bun.NewDB(c.Database, pgdialect.New())
c.Bun.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true), bundebug.FromEnv("BUNDEBUG")))
migrator := migrate.NewMigrator(c.Bun, migrations.Migrations)
err := migrator.Init(context.Background())
if err != nil {
panic(fmt.Sprintf("failed to init migrator: %v", err))
}
group, err := migrator.Migrate(context.Background())
if err != nil {
panic(fmt.Sprintf("failed to migrate db: %v", err))
}
if group.ID == 0 {
fmt.Printf("there are no new migrations to run\n")
}
fmt.Printf("migrated to %s\n", group)
}
}
// initAuth initializes the authentication client
func (c *Container) initAuth() {
c.Auth = NewAuthClient(c.Config, c.Bun)
}
// initTemplateRenderer initializes the template renderer
func (c *Container) initTemplateRenderer() {
c.TemplateRenderer = NewTemplateRenderer(c.Config)
}
// initMail initialize the mail client
func (c *Container) initMail() {
var err error
c.Mail, err = NewMailClient(c.Config, c.TemplateRenderer)
if err != nil {
panic(fmt.Sprintf("failed to create mail client: %v", err))
}
}
// initTasks initializes the task client
func (c *Container) initTasks() {
c.Tasks = NewTaskClient(c.Config)
}