Skip to content

Commit

Permalink
install & implement GORM ORM
Browse files Browse the repository at this point in the history
  • Loading branch information
Kervin Christianata committed Mar 17, 2022
1 parent e5d26a8 commit eef81cf
Show file tree
Hide file tree
Showing 9 changed files with 359 additions and 12 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.envrc
bin/
vendor/
13 changes: 13 additions & 0 deletions cmd/api/banners.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,19 @@ func (app *application) deleteBannerHandler(w http.ResponseWriter, r *http.Reque
}
}

func (app *application) gormListBannerHandler(w http.ResponseWriter, r *http.Request) {
banners, err := app.gorm.Banners.GetAll()
if err != nil {
app.serverErrorResponse(w, r, err)
return
}

err = app.writeJSON(w, http.StatusOK, http.StatusText(http.StatusOK), banners, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}

// ====================================================================================
// Business Handlers
// ====================================================================================
Expand Down
23 changes: 17 additions & 6 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import (
"sync"
"time"

"gorm.io/driver/postgres"
"gorm.io/gorm"

"github.com/kervinch/internal/data"
"github.com/kervinch/internal/jsonlog"
"github.com/kervinch/internal/mailer"
Expand Down Expand Up @@ -59,6 +62,7 @@ type application struct {
config config
logger *jsonlog.Logger
models data.Models
gorm data.Gorm
mailer mailer.Mailer
wg sync.WaitGroup
}
Expand Down Expand Up @@ -102,7 +106,7 @@ func main() {
// logger := log.New(os.Stdout, "", log.Ldate|log.Ltime)
logger := jsonlog.New(os.Stdout, jsonlog.LevelInfo)

db, err := openDB(cfg)
db, gorm, err := openDB(cfg)
if err != nil {
logger.PrintFatal(err, nil)
}
Expand All @@ -128,6 +132,7 @@ func main() {
config: cfg,
logger: logger,
models: data.NewModels(db),
gorm: data.GormModels(gorm),
mailer: mailer.New(cfg.smtp.host, cfg.smtp.port, cfg.smtp.username, cfg.smtp.password, cfg.smtp.sender),
}

Expand All @@ -137,20 +142,26 @@ func main() {
}
}

func openDB(cfg config) (*sql.DB, error) {
func openDB(cfg config) (*sql.DB, *gorm.DB, error) {
db, err := sql.Open("postgres", cfg.db.dsn)
// db, err := sql.Open("postgres", "user=postgres password= dbname=greenlight sslmode=disable port=5433")
if err != nil {
return nil, err
return nil, nil, err
}

gorm, err := gorm.Open(postgres.New(postgres.Config{
Conn: db,
}), &gorm.Config{})
if err != nil {
return nil, nil, err
}

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

err = db.PingContext(ctx)
if err != nil {
return nil, err
return nil, nil, err
}

return db, nil
return db, gorm, nil
}
2 changes: 2 additions & 0 deletions cmd/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ func (app *application) routes() http.Handler {
router.HandlerFunc(http.MethodPut, "/cms/banners/:id", app.fullUpdateBannerHandler)
router.HandlerFunc(http.MethodDelete, "/cms/banners/:id", app.deleteBannerHandler)

router.HandlerFunc(http.MethodGet, "/gorm/banners", app.gormListBannerHandler)

// Movies
router.HandlerFunc(http.MethodGet, "/cms/movies", app.requireActivatedUser(app.listMoviesHandler))
router.HandlerFunc(http.MethodGet, "/cms/free/movies", app.listMoviesHandler)
Expand Down
19 changes: 17 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,26 @@ require (
github.com/go-mail/mail/v2 v2.3.0
github.com/julienschmidt/httprouter v1.3.0
github.com/lib/pq v1.10.4
golang.org/x/crypto v0.0.0-20220128200615-198e4374d7ed
golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11
gorm.io/driver/postgres v1.3.1
gorm.io/gorm v1.23.2
)

require github.com/jmespath/go-jmespath v0.4.0 // indirect
require (
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.11.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.2.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.10.0 // indirect
github.com/jackc/pgx/v4 v4.15.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
golang.org/x/text v0.3.7 // indirect
)

require (
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce
Expand Down
186 changes: 183 additions & 3 deletions go.sum

Large diffs are not rendered by default.

51 changes: 51 additions & 0 deletions internal/data/gorm_banner.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package data

import (
"time"

"github.com/kervinch/internal/validator"
"gorm.io/gorm"
)

type BannerTemp struct {
ID int64 `json:"id" gorm:"primaryKey"`
ImageURL string `json:"image_url"`
Title string `json:"title"`
Deeplink string `json:"deeplink"`
OutboundURL string `json:"outbound_url"`
IsActive bool `json:"is_active"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
}

func GormValidateBanner(v *validator.Validator, banner *Banner) {
v.Check(banner.ImageURL != "", "image_url", "must be provided")
v.Check(banner.Title != "", "title", "must be provided")
v.Check(len(banner.Title) <= 500, "title", "must not be more than 500 bytes long")
v.Check(len(banner.Deeplink) <= 500, "deeplink", "must not be more than 500 bytes long")
v.Check(len(banner.OutboundURL) <= 500, "outbound_url", "must not be more than 500 bytes long")
}

type GormBannerModel struct {
DB *gorm.DB
}

// ====================================================================================
// Backoffice Functions
// ====================================================================================

func (g GormBannerModel) GetAll() ([]*Banner, error) {
var banners []*Banner

err := g.DB.Find(&banners).Error

if err != nil {
return nil, err
}

return banners, nil
}

// ====================================================================================
// Business Functions
// ====================================================================================
12 changes: 12 additions & 0 deletions internal/data/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package data
import (
"database/sql"
"errors"

"gorm.io/gorm"
)

var (
Expand All @@ -18,6 +20,10 @@ type Models struct {
Banners BannerModel
}

type Gorm struct {
Banners GormBannerModel
}

func NewModels(db *sql.DB) Models {
return Models{
Movies: MovieModel{DB: db},
Expand All @@ -28,6 +34,12 @@ func NewModels(db *sql.DB) Models {
}
}

func GormModels(db *gorm.DB) Gorm {
return Gorm{
Banners: GormBannerModel{DB: db},
}
}

// func NewMockModels() Models {
// return Models{
// Movies: MockMovieModel{},
Expand Down
64 changes: 63 additions & 1 deletion vendor/modules.txt
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,40 @@ github.com/felixge/httpsnoop
# github.com/go-mail/mail/v2 v2.3.0
## explicit
github.com/go-mail/mail/v2
# github.com/jackc/chunkreader/v2 v2.0.1
## explicit; go 1.12
github.com/jackc/chunkreader/v2
# github.com/jackc/pgconn v1.11.0
## explicit; go 1.12
github.com/jackc/pgconn
github.com/jackc/pgconn/internal/ctxwatch
github.com/jackc/pgconn/stmtcache
# github.com/jackc/pgio v1.0.0
## explicit; go 1.12
github.com/jackc/pgio
# github.com/jackc/pgpassfile v1.0.0
## explicit; go 1.12
github.com/jackc/pgpassfile
# github.com/jackc/pgproto3/v2 v2.2.0
## explicit; go 1.12
github.com/jackc/pgproto3/v2
# github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b
## explicit; go 1.14
github.com/jackc/pgservicefile
# github.com/jackc/pgtype v1.10.0
## explicit; go 1.13
github.com/jackc/pgtype
# github.com/jackc/pgx/v4 v4.15.0
## explicit; go 1.13
github.com/jackc/pgx/v4
github.com/jackc/pgx/v4/internal/sanitize
github.com/jackc/pgx/v4/stdlib
# github.com/jinzhu/inflection v1.0.0
## explicit
github.com/jinzhu/inflection
# github.com/jinzhu/now v1.1.5
## explicit; go 1.12
github.com/jinzhu/now
# github.com/jmespath/go-jmespath v0.4.0
## explicit; go 1.14
github.com/jmespath/go-jmespath
Expand All @@ -61,10 +95,26 @@ github.com/lib/pq/scram
# github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce
## explicit
github.com/tomasen/realip
# golang.org/x/crypto v0.0.0-20220128200615-198e4374d7ed
# golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd
## explicit; go 1.17
golang.org/x/crypto/bcrypt
golang.org/x/crypto/blowfish
golang.org/x/crypto/pbkdf2
# golang.org/x/text v0.3.7
## explicit; go 1.17
golang.org/x/text/cases
golang.org/x/text/internal
golang.org/x/text/internal/language
golang.org/x/text/internal/language/compact
golang.org/x/text/internal/tag
golang.org/x/text/language
golang.org/x/text/runes
golang.org/x/text/secure/bidirule
golang.org/x/text/secure/precis
golang.org/x/text/transform
golang.org/x/text/unicode/bidi
golang.org/x/text/unicode/norm
golang.org/x/text/width
# golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11
## explicit
golang.org/x/time/rate
Expand All @@ -73,3 +123,15 @@ golang.org/x/time/rate
gopkg.in/alexcesaro/quotedprintable.v3
# gopkg.in/mail.v2 v2.3.1
## explicit
# gorm.io/driver/postgres v1.3.1
## explicit; go 1.14
gorm.io/driver/postgres
# gorm.io/gorm v1.23.2
## explicit; go 1.14
gorm.io/gorm
gorm.io/gorm/callbacks
gorm.io/gorm/clause
gorm.io/gorm/logger
gorm.io/gorm/migrator
gorm.io/gorm/schema
gorm.io/gorm/utils

0 comments on commit eef81cf

Please sign in to comment.