Skip to content

Commit

Permalink
Use sqlite as default datastore
Browse files Browse the repository at this point in the history
Signed-off-by: Imre Nagi <[email protected]>
  • Loading branch information
imrenagi committed Jun 29, 2021
1 parent 408eb19 commit 49fe0e7
Show file tree
Hide file tree
Showing 13 changed files with 100 additions and 110 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ Thumbs.db
_output/
bin/
vendor/

example/server/gorm.db
11 changes: 5 additions & 6 deletions datastore/mysql/invoice.go → datastore/sql/invoice.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package mysql
package sql

import (
"context"
"fmt"

"github.com/imrenagi/go-payment"
"github.com/imrenagi/go-payment/invoice"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
"github.com/rs/zerolog"
)

Expand Down Expand Up @@ -45,13 +45,12 @@ func (r *InvoiceRepository) FindByNumber(ctx context.Context, number string) (*i
Preload("BillingAddress").
Where("number = ?", number).Find(&invoice)

if req.RecordNotFound() {
if req.Error == gorm.ErrRecordNotFound {
return nil, fmt.Errorf("invoice %s %w", number, payment.ErrNotFound)
}

errs := req.GetErrors()
if len(errs) > 0 {
log.Error().Err(errs[0]).Msg("can't find invoice")
if req.Error != nil {
log.Error().Err(req.Error).Msg("can't find invoice")
return nil, payment.ErrDatabase
}
return &invoice, nil
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package mysql
package sql

import (
"context"
"fmt"

"github.com/imrenagi/go-payment"
"github.com/imrenagi/go-payment/gateway/midtrans"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
"github.com/rs/zerolog"
)

Expand All @@ -20,7 +20,7 @@ type MidtransTransactionRepository struct {
DB *gorm.DB
}

// Save will update the notification stored in mysql database
// Save will update the notification stored in sql database
func (m *MidtransTransactionRepository) Save(ctx context.Context, status *midtrans.TransactionStatus) error {
log := zerolog.Ctx(ctx).With().Str("function", "MidtransTransactionRepository.Save").Logger()

Expand All @@ -40,14 +40,14 @@ func (m *MidtransTransactionRepository) FindByOrderID(ctx context.Context, order
Where("order_id = ?", orderID).
First(&status)

if req.RecordNotFound() {
if req.Error == gorm.ErrRecordNotFound {
return nil, fmt.Errorf("payment status for order %s %w", orderID, payment.ErrNotFound)
}
errs := req.GetErrors()
if len(errs) > 0 {
log.Error().Err(errs[0]).Msg("cant find midtrans transaction status")
if req.Error != nil {
log.Error().Err(req.Error).Msg("cant find midtrans transaction status")
return nil, payment.ErrDatabase
}

return &status, nil

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package mysql
package sql

import (
"context"
Expand All @@ -7,7 +7,7 @@ import (
"github.com/imrenagi/go-payment/subscription"

"github.com/imrenagi/go-payment"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
"github.com/rs/zerolog"
)

Expand Down Expand Up @@ -43,14 +43,14 @@ func (r *SubscriptionRepository) FindByNumber(ctx context.Context, number string
Preload("Invoices").
Where("number = ?", number).Find(&subs)

if req.RecordNotFound() {
if req.Error == gorm.ErrRecordNotFound{
return nil, fmt.Errorf("subscription %s %w", number, payment.ErrNotFound)
}

errs := req.GetErrors()
if len(errs) > 0 {
log.Error().Err(errs[0]).Msg("can't find subscription")
if req.Error != nil {
log.Error().Err(req.Error).Msg("can't find subscription")
return nil, payment.ErrDatabase
}

return &subs, nil
}
79 changes: 42 additions & 37 deletions example/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,56 +3,61 @@ Example

To start using this module, you can try the example [server.go](/server.go)

This example is using sqlite as the datastore. If you want to change the database,
please read gorm docs for connecting to database [here](https://gorm.io/docs/connecting_to_the_database.html)
```go
package main

import (
"net/http"
"net/http"

"github.com/gorilla/mux"
"github.com/imrenagi/go-payment/datastore/inmemory"
dsmysql "github.com/imrenagi/go-payment/datastore/mysql"
"github.com/imrenagi/go-payment/gateway/midtrans"
"github.com/imrenagi/go-payment/invoice"
"github.com/imrenagi/go-payment/manage"
"github.com/imrenagi/go-payment/server"
"github.com/imrenagi/go-payment/util/db/mysql"
"github.com/imrenagi/go-payment/util/localconfig"
"github.com/rs/cors"
"github.com/rs/zerolog/log"
"github.com/gorilla/mux"
"github.com/imrenagi/go-payment/datastore/inmemory"
dsmysql "github.com/imrenagi/go-payment/datastore/sql"
"github.com/imrenagi/go-payment/gateway/midtrans"
"github.com/imrenagi/go-payment/invoice"
"github.com/imrenagi/go-payment/manage"
"github.com/imrenagi/go-payment/server"
"github.com/imrenagi/go-payment/util/db/mysql"
"github.com/imrenagi/go-payment/util/localconfig"
"github.com/rs/cors"
"github.com/rs/zerolog/log"
)

func main() {

secret, err := localconfig.LoadSecret("example/server/secret.yaml")
if err != nil {
panic(err)
}
secret, err := localconfig.LoadSecret("example/server/secret.yaml")
if err != nil {
panic(err)
}

db := mysql.NewGorm(secret.DB)
db.AutoMigrate(
&midtrans.TransactionStatus{},
&invoice.Invoice{},
&invoice.Payment{},
&invoice.CreditCardDetail{},
&invoice.LineItem{},
&invoice.BillingAddress{},
)
db, err := gorm.Open(sqlite.Open("example/server/gorm.db"), &gorm.Config{})
if err != nil {
log.Fatal().Msg(err.Error())
}
db.AutoMigrate(
&midtrans.TransactionStatus{},
&invoice.Invoice{},
&invoice.Payment{},
&invoice.CreditCardDetail{},
&invoice.LineItem{},
&invoice.BillingAddress{},
)

m := manage.NewManager(secret.Payment)
m.MustMidtransTransactionStatusRepository(dsmysql.NewMidtransTransactionRepository(db))
m.MustInvoiceRepository(dsmysql.NewInvoiceRepository(db))
m.MustPaymentConfigReader(inmemory.NewPaymentConfigRepository("example/server/payment-methods.yml"))
m := manage.NewManager(secret.Payment)
m.MustMidtransTransactionStatusRepository(dsmysql.NewMidtransTransactionRepository(db))
m.MustInvoiceRepository(dsmysql.NewInvoiceRepository(db))
m.MustPaymentConfigReader(inmemory.NewPaymentConfigRepository("example/server/payment-methods.yml"))

srv := srv{
Router: mux.NewRouter(),
paymentSrv: server.NewServer(m),
}
srv.routes()
srv := srv{
Router: mux.NewRouter(),
paymentSrv: server.NewServer(m),
}
srv.routes()

if err := http.ListenAndServe(":8080", srv.GetHandler()); err != nil {
log.Fatal().Msgf("Server can't run. Got: `%v`", err)
}
if err := http.ListenAndServe(":8080", srv.GetHandler()); err != nil {
log.Fatal().Msgf("Server can't run. Got: `%v`", err)
}

}
```
Expand Down
27 changes: 16 additions & 11 deletions example/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,21 @@ package main
import (
"net/http"

"github.com/imrenagi/go-payment/subscription"

"github.com/gorilla/mux"
"github.com/rs/cors"
"gorm.io/driver/sqlite"
"gorm.io/gorm"

"github.com/rs/zerolog/log"

"github.com/imrenagi/go-payment/datastore/inmemory"
dsmysql "github.com/imrenagi/go-payment/datastore/mysql"
dssql "github.com/imrenagi/go-payment/datastore/sql"
"github.com/imrenagi/go-payment/gateway/midtrans"
"github.com/imrenagi/go-payment/invoice"
"github.com/imrenagi/go-payment/manage"
"github.com/imrenagi/go-payment/server"
"github.com/imrenagi/go-payment/util/db/mysql"
"github.com/imrenagi/go-payment/subscription"
"github.com/imrenagi/go-payment/util/localconfig"
"github.com/rs/cors"
"github.com/rs/zerolog/log"
)

func main() {
Expand All @@ -25,7 +27,10 @@ func main() {
panic(err)
}

db := mysql.NewGorm(secret.DB)
db, err := gorm.Open(sqlite.Open("example/server/gorm.db"), &gorm.Config{})
if err != nil {
log.Fatal().Msg(err.Error())
}
db.AutoMigrate(
&midtrans.TransactionStatus{},
&invoice.Invoice{},
Expand All @@ -38,9 +43,9 @@ func main() {
)

m := manage.NewManager(secret.Payment)
m.MustMidtransTransactionStatusRepository(dsmysql.NewMidtransTransactionRepository(db))
m.MustInvoiceRepository(dsmysql.NewInvoiceRepository(db))
m.MustSubscriptionRepository(dsmysql.NewSubscriptionRepository(db))
m.MustMidtransTransactionStatusRepository(dssql.NewMidtransTransactionRepository(db))
m.MustInvoiceRepository(dssql.NewInvoiceRepository(db))
m.MustSubscriptionRepository(dssql.NewSubscriptionRepository(db))
m.MustPaymentConfigReader(inmemory.NewPaymentConfigRepository("example/server/payment-methods.yaml"))

srv := srv{
Expand All @@ -66,7 +71,7 @@ func (s *srv) GetHandler() http.Handler {
AllowedOrigins: []string{"http://localhost:3000", "https://localhost:3000"},
AllowedMethods: []string{"POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "Mode"},
MaxAge: 60, //1 minutes
MaxAge: 60, // 1 minutes
AllowCredentials: true,
OptionsPassthrough: false,
Debug: false,
Expand Down
4 changes: 2 additions & 2 deletions gateway/midtrans/transaction_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
// TransactionStatus is object used to store notification from midtrans
type TransactionStatus struct {
ID uint64 `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"created_at" gorm:"not null;default:CURRENT_TIMESTAMP"`
UpdatedAt time.Time `json:"updated_at" gorm:"not null;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
CreatedAt time.Time `json:"created_at" gorm:"not null;"`
UpdatedAt time.Time `json:"updated_at" gorm:"not null;"`
StatusCode string `json:"status_code" gorm:"not null"`
StatusMessage string `json:"status_message" gorm:"type:text;not null"`
SignKey string `json:"signature_key" gorm:"type:text;column:signature_key;not null"`
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ require (
github.com/go-sql-driver/mysql v1.5.0
github.com/google/uuid v1.1.1
github.com/gorilla/mux v1.7.4
github.com/jinzhu/gorm v1.9.12
github.com/lib/pq v1.3.0 // indirect
github.com/rs/cors v1.7.0
github.com/rs/zerolog v1.18.0
Expand All @@ -19,6 +18,8 @@ require (
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073 // indirect
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4 // indirect
gopkg.in/yaml.v2 v2.2.8
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.11
)

replace github.com/veritrans/go-midtrans v0.0.0-20200303064216-54da2d269748 => github.com/schoters/go-midtrans v0.0.0-20200301123106-412075ea875d
14 changes: 12 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,13 @@ github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgf
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/jinzhu/gorm v1.9.12 h1:Drgk1clyWT9t9ERbzHza6Mj/8FY/CqMyVzOiHviMo6Q=
github.com/jinzhu/gorm v1.9.12/go.mod h1:vhTjlKSJUTWNtcbQtrMBFCxy7eXTzeCAzfL5fBZT/Qs=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M=
github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI=
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
Expand All @@ -95,6 +96,8 @@ github.com/lib/pq v1.3.0 h1:/qkRGz8zljWiDcFvgpwUpwIAPu3r07TDvs3Rws+o/pU=
github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/mattn/go-sqlite3 v2.0.1+incompatible h1:xQ15muvnzGBHpIpdrNi1DA5x0+TcBZzsIDwmw9uTHzw=
github.com/mattn/go-sqlite3 v2.0.1+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
Expand Down Expand Up @@ -232,4 +235,11 @@ gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
gorm.io/gorm v1.9.12 h1:Drgk1clyWT9t9ERbzHza6Mj/8FY/CqMyVzOiHviMo6Q=
gorm.io/gorm v1.9.12/go.mod h1:vhTjlKSJUTWNtcbQtrMBFCxy7eXTzeCAzfL5fBZT/Qs=
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.21.11 h1:CxkXW6Cc+VIBlL8yJEHq+Co4RYXdSLiMKNvgoZPjLK4=
gorm.io/gorm v1.21.11/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
4 changes: 3 additions & 1 deletion invoice/invoice.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"encoding/json"
"time"

"gorm.io/gorm"

"github.com/imrenagi/go-payment"
"github.com/imrenagi/go-payment/config"

Expand Down Expand Up @@ -121,7 +123,7 @@ func (i *Invoice) Clear() {

// AfterFind assign a state controller after the entity is fetched from
// database
func (i *Invoice) AfterFind() error {
func (i *Invoice) AfterFind(tx *gorm.DB) error {
i.StateController = NewState(i.State.String())
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/imrenagi/go-payment/gateway/xendit"
"github.com/imrenagi/go-payment/invoice"
"github.com/imrenagi/go-payment/manage"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
mgo "github.com/veritrans/go-midtrans"
)

Expand Down
4 changes: 2 additions & 2 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import "time"
// Model is base for database struct
type Model struct {
ID uint64 `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"created_at" gorm:"not null;default:CURRENT_TIMESTAMP"`
UpdatedAt time.Time `json:"updated_at" gorm:"not null;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
CreatedAt time.Time `json:"created_at" gorm:"not null;"`
UpdatedAt time.Time `json:"updated_at" gorm:"not null;"`
DeletedAt *time.Time `json:"deleted_at" sql:"index"`
}

Expand Down
Loading

0 comments on commit 49fe0e7

Please sign in to comment.