Skip to content

Commit

Permalink
Adds more repository methods and configs. Refs #3
Browse files Browse the repository at this point in the history
  • Loading branch information
ariel17 committed Mar 7, 2023
1 parent ab5c5a4 commit 10966a2
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 23 deletions.
22 changes: 2 additions & 20 deletions pkg/configs/db.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
package configs

import (
"log"
"os"

"gorm.io/driver/mysql"
"gorm.io/gorm"
)

const (
dsnKey = "DATABASE_DSN"
dsnKey = "DATABASE_DSN"
statusQueryKey = "DATABASE_STATUS_QUERY"
)

Expand All @@ -29,21 +25,7 @@ func GetStatusQuery() string {
return statusQuery
}

// GetDB returns a GORM object connected to database, if everything goes well.
func GetDB() *gorm.DB {
log.Printf("Connecting to database with DSN: %s", dsn)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
return db
}

func loadDBConfig() {
func init() {
dsn = os.Getenv(dsnKey)
statusQuery = os.Getenv(statusQueryKey)
}

func init() {
loadDBConfig()
}
10 changes: 8 additions & 2 deletions pkg/repositories/mysql_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

_ "github.com/go-sql-driver/mysql"

"github.com/ariel17/be-challenge-arios/pkg/configs"
"github.com/ariel17/be-challenge-arios/pkg/models"
)

Expand All @@ -16,8 +17,8 @@ type mysqlRepository struct {
db *sql.DB
}

func (m *mysqlRepository) Connect(dsn string) error {
db, err := sql.Open("mysql", dsn)
func (m *mysqlRepository) Connect() error {
db, err := sql.Open("mysql", configs.GetDSN())
if err != nil {
return err
}
Expand All @@ -32,6 +33,11 @@ func (m *mysqlRepository) Close() error {
return nil
}

func (m *mysqlRepository) GetStatus() error {
_, err := m.db.Query(configs.GetStatusQuery())
return err
}

func (m *mysqlRepository) AddPerson(person models.Person) error {
query := "INSERT INTO `persons` (`id`, `name`, `date_of_birth`, `nationality`) VALUES (?, ?, ?, ?)"
_, err := m.db.Exec(query, person.ID, person.Name, person.DateOfBirth, person.Nationality)
Expand Down
3 changes: 2 additions & 1 deletion pkg/repositories/repositories.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package repositories
import "github.com/ariel17/be-challenge-arios/pkg/models"

type Repository interface {
Connect(dsn string) error
Connect() error
Close() error
GetStatus() error

AddPerson(person models.Person) error
AddTeam(team models.Team) error
Expand Down

0 comments on commit 10966a2

Please sign in to comment.