Skip to content

Commit

Permalink
Change from gorm to bun
Browse files Browse the repository at this point in the history
  • Loading branch information
QUDUSKUNLE committed Oct 5, 2023
1 parent 4711059 commit 73892fb
Show file tree
Hide file tree
Showing 14 changed files with 81 additions and 69 deletions.
11 changes: 8 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ go 1.20
require (
github.com/gin-gonic/gin v1.9.1
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/google/uuid v1.3.0
github.com/google/uuid v1.3.1
github.com/joho/godotenv v1.5.1
github.com/satori/go.uuid v1.2.0
gorm.io/driver/postgres v1.5.2
)

require (
Expand All @@ -21,9 +19,16 @@ require (
github.com/kr/text v0.2.0 // indirect
github.com/rogpeppe/go-internal v1.10.0 // indirect
github.com/stretchr/testify v1.8.4 // indirect
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
github.com/uptrace/bun v1.1.16 // indirect
github.com/uptrace/bun/dialect/pgdialect v1.1.16 // indirect
github.com/uptrace/bun/driver/pgdriver v1.1.16 // indirect
github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
go.opentelemetry.io/otel v1.19.0 // indirect
go.opentelemetry.io/otel/metric v1.19.0 // indirect
go.opentelemetry.io/otel/trace v1.19.0 // indirect
mellium.im/sasl v0.3.1 // indirect
)

require (
Expand Down
17 changes: 17 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
Expand Down Expand Up @@ -78,6 +80,7 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
Expand All @@ -86,10 +89,22 @@ github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo=
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/uptrace/bun v1.1.16 h1:cn9cgEMFwcyYRsQLfxCRMUxyK1WaHwOVrR3TvzEFZ/A=
github.com/uptrace/bun v1.1.16/go.mod h1:7HnsMRRvpLFUcquJxp22JO8PsWKpFQO/gNXqqsuGWg8=
github.com/uptrace/bun/dialect/pgdialect v1.1.16 h1:eUPZ+YCJ69BA+W1X1ZmpOJSkv1oYtinr0zCXf7zCo5g=
github.com/uptrace/bun/dialect/pgdialect v1.1.16/go.mod h1:KQjfx/r6JM0OXfbv0rFrxAbdkPD7idK8VitnjIV9fZI=
github.com/uptrace/bun/driver/pgdriver v1.1.16 h1:b/NiSXk6Ldw7KLfMLbOqIkm4odHd7QiNOCPLqPFJjK4=
github.com/uptrace/bun/driver/pgdriver v1.1.16/go.mod h1:Rmfbc+7lx1z/umjMyAxkOHK81LgnGj71XC5YpA6k1vU=
github.com/vmihailenco/msgpack/v5 v5.3.5 h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU=
github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.45.0 h1:0KYeVr81ogcVRLXVcXFuPQMNZngplnP8MqrE8CqvHeg=
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.45.0/go.mod h1:ro3eEFOynMu0p59YVUFFbkOeaPREbqc5yDR2HnGpFc0=
go.opentelemetry.io/otel v1.19.0 h1:MuS/TNf4/j4IXsZuJegVzI1cwut7Qc00344rgH7p8bs=
Expand Down Expand Up @@ -124,4 +139,6 @@ gorm.io/driver/postgres v1.5.2 h1:ytTDxxEv+MplXOfFe3Lzm7SjG09fcdb3Z/c056DTBx0=
gorm.io/driver/postgres v1.5.2/go.mod h1:fmpX0m2I1PKuR7mKZiEluwrP3hbs+ps7JIGMUBpCgl8=
gorm.io/gorm v1.25.1 h1:nsSALe5Pr+cM3V1qwwQ7rOkw+6UeLrX5O4v3llhHa64=
gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
mellium.im/sasl v0.3.1 h1:wE0LW6g7U83vhvxjC1IY8DnXM+EU095yeo8XClvCdfo=
mellium.im/sasl v0.3.1/go.mod h1:xm59PUYpZHhgQ9ZqoJ5QaCqzWMi8IeS49dhp6plPCzw=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
2 changes: 1 addition & 1 deletion internal/adapters/handlers/address.handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func (service *HTTPHandler) SaveAddress(ctx *gin.Context) {
StreetName: address.StreetName,
Province: address.Province,
State: address.State,
ProfileID: profile.ID,
Profile: *profile,
}); err != nil {
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
Expand Down
10 changes: 3 additions & 7 deletions internal/adapters/handlers/profile.handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"net/http"
"os"
"strings"
"github.com/satori/go.uuid"
"github.com/google/uuid"
"server/internal/core/domain"
"github.com/gin-gonic/gin"
)
Expand All @@ -20,16 +20,12 @@ func (service *HTTPHandler) SaveProfile(ctx *gin.Context) {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized", "status": false })
return
}
result, err := uuid.FromString(UserID.(string))
if err != nil {
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error(), "status": false})
return
}
result := UserID.(uuid.UUID)
if err := service.ServicesAdapter.SaveProfile(
domain.Profile{
FirstName: strings.TrimSpace(profileDto.FirstName),
LastName: strings.TrimSpace(profileDto.LastName),
UserID: &result,
UserID: result,
}); err != nil {
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error(), "status": false})
return
Expand Down
9 changes: 5 additions & 4 deletions internal/adapters/repository/address.repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@ import (
)

func (repo *PostgresRepository) SaveAddress(address domain.Address) error {
if err := repo.db.Create(&address).Error; err != nil {
_, err := repo.db.NewInsert().Model(address).Exec(ctx)
if err != nil {
return err
}
return nil
}

func (repo *PostgresRepository) ReadAddress(AddressID string) (*domain.Address, error) {
address := &domain.Address{}
if err := repo.db.First(&address, "id = ?", AddressID).Error; err != nil {
address := new(domain.Address)
if err := repo.db.NewSelect().Model(address).Where("id = ?", AddressID).Scan(ctx); err != nil {
return &domain.Address{}, err
}
return address, nil
}

func (repo *PostgresRepository) ReadAddresses() ([]*domain.Address, error) {
var addresses []*domain.Address
repo.db.Find(&addresses)
repo.db.NewSelect().Model(addresses).Limit(20)
return addresses, nil
}
31 changes: 13 additions & 18 deletions internal/adapters/repository/postgres.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,26 @@
package repository

import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"context"
"database/sql"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
domain "server/internal/core/domain"
)

var ctx = context.Background()

type PostgresRepository struct {
db *gorm.DB
db *bun.DB
}

func PostgresDatabaseAdapter(host, port, user, password, dbname string) *PostgresRepository {
conn := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable",
host,
port,
user,
dbname,
password,
)
db, err := gorm.Open(postgres.Open(conn), &gorm.Config{})
if err != nil {
panic("Failed to connect to database")
} else {
fmt.Println("Successfully connected to the database.")
}
db.AutoMigrate(&domain.User{}, &domain.Profile{}, &domain.Address{})
dsn := "postgres://" + user + ":" + password + "@" + host + ":" + port + "/" + dbname + "?sslmode=disable"
sqlDatabase := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
db := bun.NewDB(sqlDatabase, pgdialect.New())

db.NewCreateTable().Model((*domain.User)(nil)).IfNotExists().Exec(ctx)
return &PostgresRepository{
db: db,
}
Expand Down
14 changes: 7 additions & 7 deletions internal/adapters/repository/profile.respository.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
package repository

import (
"gorm.io/gorm/clause"
domain "server/internal/core/domain"
)

func (repo *PostgresRepository) SaveProfile(profile domain.Profile) error {
if err := repo.db.Create(&profile).Error; err != nil {
_, err := repo.db.NewInsert().Model(profile).Exec(ctx)
if err != nil {
return err
}
return nil
}

func (repo *PostgresRepository) ReadProfile(ProfileID string) (*domain.Profile, error) {
profile := &domain.Profile{}
if err := repo.db.Preload(clause.Associations).Where("ID = ?", ProfileID).First(&profile).Error; err != nil {
profile := new(domain.Profile)
if err := repo.db.NewSelect().Model(profile).Where("ID = ?", ProfileID).Scan(ctx); err != nil {
return &domain.Profile{}, err
}
return profile, nil
}

func (repo *PostgresRepository) ReadProfiles() ([]*domain.Profile, error) {
var profiles []*domain.Profile
repo.db.Preload(clause.Associations).Find(&profiles)
repo.db.NewSelect().Model(profiles).Limit(20)
return profiles, nil
}

func (repo *PostgresRepository) ReadProfileByUserID(UserID string) (*domain.Profile, error) {
var profile *domain.Profile
if err := repo.db.Preload(clause.Associations).Where("user_id = ?", UserID).First(&profile).Error; err != nil {
profile := new(domain.Profile)
if err := repo.db.NewSelect().Model(profile).Where("user_id = ?", UserID).Scan(ctx); err != nil {
return &domain.Profile{}, err
}
return profile, nil
Expand Down
13 changes: 7 additions & 6 deletions internal/adapters/repository/user.repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,30 @@ import (
)

func (repo *PostgresRepository) SaveUser(user domain.User) error {
if err := repo.db.Create(&user).Error; err != nil {
_, err := repo.db.NewInsert().Model(&user).Exec(ctx)
if err != nil {
return err
}
return nil
}

func (repo *PostgresRepository) ReadUser(UserID string) (*domain.User, error) {
user := &domain.User{}
if err := repo.db.Where("ID = ?", UserID).First(&user).Error; err != nil {
user := new(domain.User)
if err := repo.db.NewSelect().Model(user).Where("ID = ?", UserID).Scan(ctx); err != nil {
return &domain.User{}, err
}
return user, nil
}

func (repo *PostgresRepository) ReadUsers() ([]*domain.User, error) {
var users []*domain.User
repo.db.Find(&users)
repo.db.NewSelect().Model(users).Limit(20)
return users, nil
}

func (repo *PostgresRepository) ReadUserByEmail(Email string) (*domain.User, error) {
user := &domain.User{}
if err := repo.db.Where(&domain.User{Email: Email}).First(&user).Error; err != nil {
user := new(domain.User)
if err := repo.db.NewSelect().Model(user).Where("Email = ? ", Email).Scan(ctx); err != nil {
return &domain.User{}, err
}
return user, nil
Expand Down
6 changes: 3 additions & 3 deletions internal/core/domain/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ package domain

import (
"time"
"github.com/satori/go.uuid"
"github.com/google/uuid"
)

type Address struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey" json:"AddressID"`
ID uuid.UUID `gorm:"type:uuid;primary_key" json:"AddressID"`
StreetNo int `gorm:"not null" sql:"unique:idx_streetno_streetname" json:"StreetNo"`
StreetName string `gorm:"not null" sql:"unique:idx_streetno_streetname" json:"StreetName"`
Province string `gorm:"not null" json:"Province"`
State string `gorm:"not null" json:"State"`
ProfileID uuid.UUID
Profile Profile
CreatedAt time.Time
UpdatedAt time.Time
}
Expand Down
13 changes: 7 additions & 6 deletions internal/core/domain/profile.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package domain

import (
"github.com/satori/go.uuid"
"github.com/google/uuid"
"time"
)

type Profile struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey" json:"ProfileID"`
FirstName string `gorm:"size:50;index:idx_full_name" json:"FirstName"`
LastName string `gorm:"size:50;index:idx_full_name" json:"LastName"`
UserID *uuid.UUID `gorm:"foreignKey:ID" json:"-"`
Addresses []Address `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" json:"Addresses"`
ID uuid.UUID `bun:"type:uuid,pk" json:"ProfileID"`
FirstName string `json:"FirstName"`
LastName string `json:"LastName"`
UserID uuid.UUID `bun:"type:uuid"`
User User `bun:"rel:belongs-to,join:user_id=id"`
Addresses []Address `json:"Addresses"`
CreatedAt time.Time
UpdatedAt time.Time
}
Expand Down
17 changes: 10 additions & 7 deletions internal/core/domain/user.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
package domain

import (
"time"
"errors"
"github.com/satori/go.uuid"
"time"

"github.com/google/uuid"
"github.com/uptrace/bun"
"golang.org/x/crypto/bcrypt"
)

type User struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey" json:"UserID"`
Email string `gorm:"size:255;unique" json:"Email"`
Password string `gorm:"size:255;" json:"-"`
Role string `gorm:"type:string;default:customer" json:"Role"`
Profile Profile
bun.BaseModel `bun:"table:users"`

ID uuid.UUID `bun:",pk,type:uuid,default:uuid_generate_v4()"`
Email string `bun:"email,unique"`
Password string `bun:"password"`
Role string `bun:"role,default:customer"`
CreatedAt time.Time
UpdatedAt time.Time
}
Expand Down
2 changes: 0 additions & 2 deletions internal/core/services/address.services.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package services

import (
"github.com/satori/go.uuid"
domain "server/internal/core/domain"
)

func (externalServiceHandler *ServicesHandler) SaveAddress(address domain.Address) error {
address.ID = uuid.NewV4()
return externalServiceHandler.Internal.SaveAddress(address)
}

Expand Down
2 changes: 0 additions & 2 deletions internal/core/services/profile.services.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package services

import (
"github.com/satori/go.uuid"
domain "server/internal/core/domain"
)

func (externalServiceHandler *ServicesHandler) SaveProfile(profile domain.Profile) error {
profile.ID = uuid.NewV4()
return externalServiceHandler.Internal.SaveProfile(profile)
}

Expand Down
3 changes: 0 additions & 3 deletions internal/core/services/users.services.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,12 @@ import (
"fmt"
"html"
"strings"
"github.com/satori/go.uuid"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/bcrypt"
domain "server/internal/core/domain"
)

func (externalServiceHandler *ServicesHandler) SaveUser(user domain.User) error {
user.ID = uuid.NewV4()
hashedPassword, err := bcrypt.GenerateFromPassword(
[]byte(user.Password),
bcrypt.DefaultCost,
Expand All @@ -40,7 +38,6 @@ func (externalServiceHandler *ServicesHandler) ReadUserByEmail(Email string) (*d

func (externalServiceHandler *ServicesHandler) Login(user domain.UserDto) (string, error) {
userByEmail, err := externalServiceHandler.Internal.ReadUserByEmail(user.Email)
fmt.Println(userByEmail, err, "@@@@@@@")
if err != nil {
fmt.Println(err)
return "", err
Expand Down

0 comments on commit 73892fb

Please sign in to comment.