-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Himitsuko
committed
Nov 11, 2022
1 parent
6665501
commit 9266a70
Showing
3 changed files
with
341 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package connection | ||
|
||
import ( | ||
"fmt" | ||
"github.com/caarlos0/env/v6" | ||
"go.uber.org/zap" | ||
"gorm.io/driver/postgres" | ||
"gorm.io/gorm" | ||
"gorm.io/gorm/schema" | ||
"log" | ||
"moul.io/zapgorm2" | ||
) | ||
|
||
type Config struct { | ||
URL string `env:"DATABASE_URL"` | ||
Host string `env:"DATABASE_HOST"` | ||
Port int32 `env:"DATABASE_PORT"` | ||
User string `env:"DATABASE_USER"` | ||
Password string `env:"DATABASE_PASSWORD"` | ||
Database string `env:"DATABASE_DB"` | ||
Environment string `env:"GIN_MODE"` | ||
AppName string `env:"APP_NAME"` | ||
} | ||
|
||
func NewConnection(log *zap.Logger, sch *string) *gorm.DB { | ||
config := parseConfig() | ||
connection := config.ToConnectionURI() | ||
logger := zapgorm2.New(log) | ||
logger.SetAsDefault() | ||
|
||
public := "public" | ||
if sch == nil { | ||
sch = &public | ||
} | ||
db, err := gorm.Open(postgres.Open(connection), &gorm.Config{ | ||
NamingStrategy: schema.NamingStrategy{ | ||
TablePrefix: *sch + ".", | ||
SingularTable: false, | ||
}, | ||
Logger: logger, | ||
}) | ||
if err != nil { | ||
log.Error(err.Error()) | ||
} | ||
return db | ||
} | ||
|
||
func (c Config) ToConnectionURI() string { | ||
return fmt.Sprintf(`postgresql://%s:%s@%s:%v/%s?application_name=%s`, c.User, c.Password, c.Host, c.Port, c.Database, c.AppName) | ||
} | ||
|
||
func parseConfig() *Config { | ||
c := Config{} | ||
if err := env.Parse(&c); err != nil { | ||
log.Fatal(err) | ||
} | ||
return &c | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.