From 81505baf7a945b2c9f10ad3dc4eac6a78bb61f10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=20Jurmanovi=C4=87?= Date: Wed, 30 Jun 2021 21:55:47 +0200 Subject: [PATCH 1/3] grouped transactions --- pkg/services/subscriptions.go | 10 +++++++--- pkg/services/transactions.go | 9 +++++++-- pkg/services/users.go | 18 ++++++++++++++---- pkg/services/wallets.go | 9 +++++++-- 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/pkg/services/subscriptions.go b/pkg/services/subscriptions.go index 7f0963a..3d6d6bb 100644 --- a/pkg/services/subscriptions.go +++ b/pkg/services/subscriptions.go @@ -57,6 +57,9 @@ func (as *SubscriptionService) GetAll(am *models.Auth, walletId string, filtered } func (as *SubscriptionService) SubToTrans(subModel *models.Subscription) { + tx, _ := as.Db.Begin() + defer tx.Rollback() + now := time.Now() currentYear, currentMonth, _ := now.Date() @@ -75,7 +78,7 @@ func (as *SubscriptionService) SubToTrans(subModel *models.Subscription) { if subModel.SubscriptionType == nil { st := new(models.SubscriptionType) - as.Db.Model(st).Where("? = ?", pg.Ident("id"), subModel.SubscriptionTypeID).Select() + tx.Model(st).Where("? = ?", pg.Ident("id"), subModel.SubscriptionTypeID).Select() subModel.SubscriptionType = st } @@ -98,10 +101,11 @@ func (as *SubscriptionService) SubToTrans(subModel *models.Subscription) { if len(*transactions) > 0 { for _, trans := range *transactions { - _, err := as.Db.Model(&trans).Where("? = ?", pg.Ident("transaction_date"), trans.TransactionDate).Where("? = ?", pg.Ident("subscription_id"), trans.SubscriptionID).OnConflict("DO NOTHING").SelectOrInsert() + _, err := tx.Model(&trans).Where("? = ?", pg.Ident("transaction_date"), trans.TransactionDate).Where("? = ?", pg.Ident("subscription_id"), trans.SubscriptionID).OnConflict("DO NOTHING").SelectOrInsert() if err != nil { - as.Db.Model(subModel).Set("? = ?", pg.Ident("last_transaction_date"), trans.TransactionDate).WherePK().Update() + tx.Model(subModel).Set("? = ?", pg.Ident("last_transaction_date"), trans.TransactionDate).WherePK().Update() } } } + tx.Commit() } diff --git a/pkg/services/transactions.go b/pkg/services/transactions.go index 43d9784..4580e0c 100644 --- a/pkg/services/transactions.go +++ b/pkg/services/transactions.go @@ -38,7 +38,10 @@ func (as *TransactionService) GetAll(am *models.Auth, walletId string, filtered wm := new([]models.Transaction) sm := new([]models.Subscription) - query2 := as.Db.Model(sm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) + tx, _ := as.Db.Begin() + defer tx.Rollback() + + query2 := tx.Model(sm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) if walletId != "" { query2 = query2.Where("? = ?", pg.Ident("wallet_id"), walletId) } @@ -48,9 +51,11 @@ func (as *TransactionService) GetAll(am *models.Auth, walletId string, filtered as.Ss.SubToTrans(&sub) } - query := as.Db.Model(wm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) + query := tx.Model(wm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) if walletId != "" { query = query.Where("? = ?", pg.Ident("wallet_id"), walletId) } FilteredResponse(query, wm, filtered) + + tx.Commit() } diff --git a/pkg/services/users.go b/pkg/services/users.go index 2b979b1..04edcec 100644 --- a/pkg/services/users.go +++ b/pkg/services/users.go @@ -21,7 +21,10 @@ func (us *UsersService) Create(registerBody *models.User) (*models.User, *models check := new(models.User) exceptionReturn := new(models.Exception) - us.Db.Model(check).Where("? = ?", pg.Ident("username"), registerBody.Username).WhereOr("? = ?", pg.Ident("email"), registerBody.Email).Select() + tx, _ := us.Db.Begin() + defer tx.Rollback() + + tx.Model(check).Where("? = ?", pg.Ident("username"), registerBody.Username).WhereOr("? = ?", pg.Ident("email"), registerBody.Email).Select() if check.Username != "" || check.Email != "" { exceptionReturn.Message = "User already exists" exceptionReturn.ErrorCode = "400101" @@ -33,7 +36,7 @@ func (us *UsersService) Create(registerBody *models.User) (*models.User, *models common.CheckError(err) registerBody.Password = string(hashedPassword) - _, err = us.Db.Model(registerBody).Insert() + _, err = tx.Model(registerBody).Insert() if err != nil { exceptionReturn.Message = "Error creating user" @@ -41,6 +44,8 @@ func (us *UsersService) Create(registerBody *models.User) (*models.User, *models exceptionReturn.StatusCode = 400 } + tx.Commit() + return registerBody, exceptionReturn } @@ -84,7 +89,10 @@ func (us *UsersService) Deactivate(auth *models.Auth) (*models.MessageResponse, me := new(models.Exception) um := new(models.User) - err := us.Db.Model(um).Where("? = ?", pg.Ident("id"), auth.Id).Select() + tx, _ := us.Db.Begin() + defer tx.Rollback() + + err := tx.Model(um).Where("? = ?", pg.Ident("id"), auth.Id).Select() if err != nil { me.ErrorCode = "404101" @@ -93,7 +101,7 @@ func (us *UsersService) Deactivate(auth *models.Auth) (*models.MessageResponse, return mm, me } um.IsActive = false - _, err = us.Db.Model(um).Where("? = ?", pg.Ident("id"), auth.Id).Update() + _, err = tx.Model(um).Where("? = ?", pg.Ident("id"), auth.Id).Update() if err != nil { me.ErrorCode = "400105" @@ -104,6 +112,8 @@ func (us *UsersService) Deactivate(auth *models.Auth) (*models.MessageResponse, mm.Message = "User successfully deactivated." + tx.Commit() + return mm, me } diff --git a/pkg/services/wallets.go b/pkg/services/wallets.go index 709da31..48d183e 100644 --- a/pkg/services/wallets.go +++ b/pkg/services/wallets.go @@ -47,7 +47,10 @@ func (as *WalletService) GetHeader(am *models.Auth, walletId string) *models.Wal transactions := new([]models.Transaction) subscriptions := new([]models.Subscription) - query2 := as.Db.Model(subscriptions).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id).Relation("TransactionType").Relation("SubscriptionType") + tx, _ := as.Db.Begin() + defer tx.Rollback() + + query2 := tx.Model(subscriptions).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id).Relation("TransactionType").Relation("SubscriptionType") if walletId != "" { query2.Where("? = ?", pg.Ident("wallet_id"), walletId) } @@ -68,7 +71,7 @@ func (as *WalletService) GetHeader(am *models.Auth, walletId string) *models.Wal } } - query := as.Db.Model(transactions).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id).Relation("TransactionType") + query := tx.Model(transactions).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id).Relation("TransactionType") if walletId != "" { query.Where("? = ?", pg.Ident("wallet_id"), walletId) } @@ -117,6 +120,8 @@ func (as *WalletService) GetHeader(am *models.Auth, walletId string) *models.Wal wm.Currency = "USD" wm.WalletId = walletId + tx.Commit() + return wm } From 1b4d5e8725b9d877f6d89276f47ba7a934867ec0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=20Jurmanovi=C4=87?= Date: Wed, 30 Jun 2021 22:36:03 +0200 Subject: [PATCH 2/3] fixed low performance transactions --- pkg/models/subscriptions.go | 53 ++++++++++++++++++----------------- pkg/services/subscriptions.go | 21 ++++++++------ pkg/services/transactions.go | 5 +++- pkg/services/wallets.go | 2 +- 4 files changed, 46 insertions(+), 35 deletions(-) diff --git a/pkg/models/subscriptions.go b/pkg/models/subscriptions.go index 65a1a86..5384216 100644 --- a/pkg/models/subscriptions.go +++ b/pkg/models/subscriptions.go @@ -50,31 +50,34 @@ func (cm *Subscription) ToTrans() *Transaction { } func (cm *Subscription) HasNew() bool { - trans := cm.TransactionType; - switch trans.Type { - case "monthly": - lastDate := time.Now().AddDate(0, -cm.CustomRange, 0) - if cm.LastTransactionDate.Before(lastDate) { - return true + trans := cm.TransactionType + if trans != nil { + switch trans.Type { + case "monthly": + lastDate := time.Now().AddDate(0, -cm.CustomRange, 0) + if cm.LastTransactionDate.Before(lastDate) { + return true + } + return false + case "weekly": + lastDate := time.Now().AddDate(0, 0, -(7*cm.CustomRange)) + if cm.LastTransactionDate.Before(lastDate) { + return true + } + return false + case "daily": + lastDate := time.Now().AddDate(0, 0, -cm.CustomRange) + if cm.LastTransactionDate.Before(lastDate) { + return true + } + return false + default: + lastDate := time.Now().AddDate(-cm.CustomRange, 0, 0) + if cm.LastTransactionDate.Before(lastDate) { + return true + } + return false } - return false - case "weekly": - lastDate := time.Now().AddDate(0, 0, -(7*cm.CustomRange)) - if cm.LastTransactionDate.Before(lastDate) { - return true - } - return false - case "daily": - lastDate := time.Now().AddDate(0, 0, -cm.CustomRange) - if cm.LastTransactionDate.Before(lastDate) { - return true - } - return false - default: - lastDate := time.Now().AddDate(-cm.CustomRange, 0, 0) - if cm.LastTransactionDate.Before(lastDate) { - return true - } - return false } + return true } \ No newline at end of file diff --git a/pkg/services/subscriptions.go b/pkg/services/subscriptions.go index 3d6d6bb..1db9553 100644 --- a/pkg/services/subscriptions.go +++ b/pkg/services/subscriptions.go @@ -33,9 +33,13 @@ func (as *SubscriptionService) New(body *models.NewSubscriptionBody) *models.Sub tm.StartDate = time.Now() } - as.Db.Model(tm).Insert() + tx, _ := as.Db.Begin() + defer tx.Rollback() - as.SubToTrans(tm) + tx.Model(tm).Insert() + + as.SubToTrans(tm, tx) + tx.Commit() return tm } @@ -43,22 +47,24 @@ func (as *SubscriptionService) New(body *models.NewSubscriptionBody) *models.Sub func (as *SubscriptionService) GetAll(am *models.Auth, walletId string, filtered *models.FilteredResponse) { wm := new([]models.Subscription) - query := as.Db.Model(wm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) + tx, _ := as.Db.Begin() + defer tx.Rollback() + + query := tx.Model(wm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) if walletId != "" { query = query.Where("? = ?", pg.Ident("wallet_id"), walletId) } for _, sub := range *wm { if sub.HasNew() { - as.SubToTrans(&sub) + as.SubToTrans(&sub, tx) } } FilteredResponse(query, wm, filtered) + tx.Commit() } -func (as *SubscriptionService) SubToTrans(subModel *models.Subscription) { - tx, _ := as.Db.Begin() - defer tx.Rollback() +func (as *SubscriptionService) SubToTrans(subModel *models.Subscription, tx *pg.Tx) { now := time.Now() @@ -107,5 +113,4 @@ func (as *SubscriptionService) SubToTrans(subModel *models.Subscription) { } } } - tx.Commit() } diff --git a/pkg/services/transactions.go b/pkg/services/transactions.go index 4580e0c..d11015a 100644 --- a/pkg/services/transactions.go +++ b/pkg/services/transactions.go @@ -48,13 +48,16 @@ func (as *TransactionService) GetAll(am *models.Auth, walletId string, filtered query2.Select() for _, sub := range *sm { - as.Ss.SubToTrans(&sub) + if sub.HasNew() { + as.Ss.SubToTrans(&sub, tx) + } } query := tx.Model(wm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) if walletId != "" { query = query.Where("? = ?", pg.Ident("wallet_id"), walletId) } + FilteredResponse(query, wm, filtered) tx.Commit() diff --git a/pkg/services/wallets.go b/pkg/services/wallets.go index 48d183e..462eb92 100644 --- a/pkg/services/wallets.go +++ b/pkg/services/wallets.go @@ -67,7 +67,7 @@ func (as *WalletService) GetHeader(am *models.Auth, walletId string) *models.Wal for _, sub := range *subscriptions { if sub.HasNew() { - as.Ss.SubToTrans(&sub) + as.Ss.SubToTrans(&sub, tx) } } From 788ff3a1469c1eb8ea940a9cf715f2e60cc25108 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=20Jurmanovi=C4=87?= Date: Sat, 3 Jul 2021 00:01:25 +0200 Subject: [PATCH 3/3] upgraded migrations and context usage --- cmd/api/main.go | 4 +- cmd/migrate/main.go | 6 +- go.mod | 1 + go.sum | 20 ++++++ pkg/controllers/api.go | 6 +- pkg/controllers/auth.go | 6 +- pkg/controllers/subscriptionTypes.go | 4 +- pkg/controllers/subscriptions.go | 4 +- pkg/controllers/transactionTypes.go | 4 +- pkg/controllers/transactions.go | 4 +- pkg/controllers/wallets-header.go | 2 +- pkg/controllers/wallets.go | 6 +- pkg/middleware/secretCode.go | 10 +-- .../api.go => 1_create_table_api.go} | 11 ++- .../users.go => 2_create_table_users.go} | 11 ++- .../wallets.go => 3_create_table_wallets.go} | 12 ++-- .../4_create_table_transaction_types.go | 30 +++++++++ ...ions.go => 5_create_table_transactions.go} | 11 ++- .../6_create_table_subscription_types.go | 30 +++++++++ ...ons.go => 7_create_table_subscriptions.go} | 15 ++--- pkg/migrate/8_populate_subscription_types.go | 39 +++++++++++ pkg/migrate/9_populate_transaction_types.go | 25 +++++++ pkg/migrate/migrate.go | 61 +++++++++++------ pkg/migrate/migrations/subscriptionTypes.go | 67 ------------------- pkg/migrate/migrations/transactionTypes.go | 53 --------------- pkg/services/api.go | 18 ++--- pkg/services/subscriptionTypes.go | 13 ++-- pkg/services/subscriptions.go | 13 ++-- pkg/services/transactionTypes.go | 13 ++-- pkg/services/transactions.go | 13 ++-- pkg/services/users.go | 19 ++++-- pkg/services/wallets.go | 35 ++++++---- pkg/utl/db/db.go | 6 +- 33 files changed, 321 insertions(+), 251 deletions(-) rename pkg/migrate/{migrations/api.go => 1_create_table_api.go} (69%) rename pkg/migrate/{migrations/users.go => 2_create_table_users.go} (69%) rename pkg/migrate/{migrations/wallets.go => 3_create_table_wallets.go} (70%) create mode 100644 pkg/migrate/4_create_table_transaction_types.go rename pkg/migrate/{migrations/transactions.go => 5_create_table_transactions.go} (69%) create mode 100644 pkg/migrate/6_create_table_subscription_types.go rename pkg/migrate/{migrations/subscriptions.go => 7_create_table_subscriptions.go} (68%) create mode 100644 pkg/migrate/8_populate_subscription_types.go create mode 100644 pkg/migrate/9_populate_transaction_types.go delete mode 100644 pkg/migrate/migrations/subscriptionTypes.go delete mode 100644 pkg/migrate/migrations/transactionTypes.go diff --git a/cmd/api/main.go b/cmd/api/main.go index 3da8f4f..6af5640 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "os" "wallet-api/pkg/api" "wallet-api/pkg/middleware" @@ -14,11 +15,12 @@ import ( func main() { godotenv.Load() + ctx := context.Background() dbUrl := os.Getenv("DATABASE_URL") r := gin.New() r.Use(middleware.CORSMiddleware()) - conn := db.CreateConnection(dbUrl) + conn := db.CreateConnection(dbUrl, ctx) api.Init(r, conn) server.Start(r) diff --git a/cmd/migrate/main.go b/cmd/migrate/main.go index 98e7e9a..5827efa 100644 --- a/cmd/migrate/main.go +++ b/cmd/migrate/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "os" "wallet-api/pkg/migrate" "wallet-api/pkg/utl/db" @@ -12,7 +13,8 @@ func main() { godotenv.Load() dbUrl := os.Getenv("DATABASE_URL") + ctx := context.Background() - conn := db.CreateConnection(dbUrl) - migrate.Start(conn) + conn := db.CreateConnection(dbUrl, ctx) + migrate.Start(conn, "") } diff --git a/go.mod b/go.mod index 9d5f5e6..4c2ffc6 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.15 require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-gonic/gin v1.7.1 + github.com/go-pg/migrations/v8 v8.1.0 github.com/go-pg/pg/v10 v10.9.1 github.com/go-playground/validator/v10 v10.5.0 // indirect github.com/golang/protobuf v1.5.2 // indirect diff --git a/go.sum b/go.sum index 90a97aa..be6e788 100644 --- a/go.sum +++ b/go.sum @@ -15,7 +15,10 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.7.1 h1:qC89GU3p8TvKWMAVhEpmpB2CIb1hnqt2UdKZaP93mS8= github.com/gin-gonic/gin v1.7.1/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= +github.com/go-pg/migrations/v8 v8.1.0 h1:bc1wQwFoWRKvLdluXCRFRkeaw9xDU4qJ63uCAagh66w= +github.com/go-pg/migrations/v8 v8.1.0/go.mod h1:o+CN1u572XHphEHZyK6tqyg2GDkRvL2bIoLNyGIewus= github.com/go-pg/pg v8.0.7+incompatible h1:ty/sXL1OZLo+47KK9N8llRcmbA9tZasqbQ/OO4ld53g= +github.com/go-pg/pg/v10 v10.4.0/go.mod h1:BfgPoQnD2wXNd986RYEHzikqv9iE875PrFaZ9vXvtNM= github.com/go-pg/pg/v10 v10.9.1 h1:kU4t84zWGGaU0Qsu49FbNtToUVrlSTkNOngW8aQmwvk= github.com/go-pg/pg/v10 v10.9.1/go.mod h1:rgmTPgHgl5EN2CNKKoMwC7QT62t8BqsdpEkUQuiZMQs= github.com/go-pg/zerochecker v0.2.0 h1:pp7f72c3DobMWOb2ErtZsnrPaSvHd2W4o9//8HtF4mU= @@ -32,9 +35,11 @@ github.com/go-playground/validator/v10 v10.5.0/go.mod h1:xm76BBt941f7yWdGnI2DVPF github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= @@ -51,6 +56,7 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= @@ -109,12 +115,16 @@ github.com/ugorji/go/codec v1.2.5 h1:8WobZKAk18Msm2CothY2jnztY56YVY8kF1oQrj21iis github.com/ugorji/go/codec v1.2.5/go.mod h1:QPxoTbPKSEAlAHPYt02++xp/en9B/wUdwFCz+hj5caA= github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94= github.com/vmihailenco/bufpool v0.1.11/go.mod h1:AFf/MOy3l2CFTKbxwt0mp2MwnqjNEs5H/UxrkA5jxTQ= +github.com/vmihailenco/msgpack/v4 v4.3.11/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= +github.com/vmihailenco/msgpack/v5 v5.0.0-beta.1/go.mod h1:xlngVLeyQ/Qi05oQxhQ+oTuqa03RjMwMfk/7/TCs+QI= github.com/vmihailenco/msgpack/v5 v5.3.0 h1:8G3at/kelmBKeHY6d6cKnGsYO3BLn+uubitdOtOhyNI= github.com/vmihailenco/msgpack/v5 v5.3.0/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= +github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= github.com/vmihailenco/tagparser v0.1.2 h1:gnjoVuB/kljJ5wICEEOpx98oXMWPLj22G67Vbd1qPqc= github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= 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/otel v0.13.0/go.mod h1:dlSNewoRYikTkotEnxdmuBHgzT+k/idJSfDv/FxEnOY= go.opentelemetry.io/otel v0.19.0 h1:Lenfy7QHRXPZVsw/12CWpxX6d/JkrX8wrx2vO8G80Ng= go.opentelemetry.io/otel v0.19.0/go.mod h1:j9bF567N9EfomkSidSfmMwIwIBuP37AMAIzVW85OxSg= go.opentelemetry.io/otel/metric v0.19.0 h1:dtZ1Ju44gkJkYvo+3qGqVXmf88tc+a42edOywypengg= @@ -126,6 +136,8 @@ golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= @@ -141,8 +153,12 @@ golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201016165138-7b1cca2348c0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -160,6 +176,8 @@ golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201017003518-b09fb700fbb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210426230700-d19ff857e887 h1:dXfMednGJh/SUUFjTLsWJz3P+TQt9qnR11GgeI3vWKs= @@ -179,6 +197,8 @@ golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBn golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= diff --git a/pkg/controllers/api.go b/pkg/controllers/api.go index 4173996..35c586b 100644 --- a/pkg/controllers/api.go +++ b/pkg/controllers/api.go @@ -22,12 +22,14 @@ func NewApiController(as *services.ApiService, s *gin.RouterGroup) *ApiControlle } func (ac *ApiController) getFirst(c *gin.Context) { - apiModel := ac.ApiService.GetFirst() + apiModel := ac.ApiService.GetFirst(c) c.JSON(200, apiModel) } func (ac *ApiController) postMigrate(c *gin.Context) { - mr, er := ac.ApiService.PostMigrate() + migrateModel := c.MustGet("migrate") + version := migrateModel.(middleware.SecretCodeModel).Version + mr, er := ac.ApiService.PostMigrate(c, version) if er.Message != "" { c.JSON(er.StatusCode, er) diff --git a/pkg/controllers/auth.go b/pkg/controllers/auth.go index 1ead3a5..b732974 100644 --- a/pkg/controllers/auth.go +++ b/pkg/controllers/auth.go @@ -31,7 +31,7 @@ func (rc *AuthController) PostLogin(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - returnedUser, exceptionReturn := rc.UsersService.Login(body) + returnedUser, exceptionReturn := rc.UsersService.Login(c, body) if exceptionReturn.Message != "" { c.JSON(exceptionReturn.StatusCode, exceptionReturn) @@ -48,7 +48,7 @@ func (rc *AuthController) PostRegister(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - returnedUser, exceptionReturn := rc.UsersService.Create(body) + returnedUser, exceptionReturn := rc.UsersService.Create(c, body) if exceptionReturn.Message != "" { c.JSON(exceptionReturn.StatusCode, exceptionReturn) @@ -61,7 +61,7 @@ func (rc *AuthController) Delete(c *gin.Context) { authGet := c.MustGet("auth") auth.Id = authGet.(*models.Auth).Id - mr, er := rc.UsersService.Deactivate(auth) + mr, er := rc.UsersService.Deactivate(c, auth) if er.Message != "" { c.JSON(er.StatusCode, er) diff --git a/pkg/controllers/subscriptionTypes.go b/pkg/controllers/subscriptionTypes.go index a71c9fa..cf120fe 100644 --- a/pkg/controllers/subscriptionTypes.go +++ b/pkg/controllers/subscriptionTypes.go @@ -29,14 +29,14 @@ func (wc *SubscriptionTypeController) New(c *gin.Context) { return } - wm := wc.SubscriptionTypeService.New(body) + wm := wc.SubscriptionTypeService.New(c, body) c.JSON(200, wm) } func (wc *SubscriptionTypeController) GetAll(c *gin.Context) { embed, _ := c.GetQuery("embed") - wm := wc.SubscriptionTypeService.GetAll(embed) + wm := wc.SubscriptionTypeService.GetAll(c, embed) c.JSON(200, wm) } diff --git a/pkg/controllers/subscriptions.go b/pkg/controllers/subscriptions.go index d11a316..eac96ad 100644 --- a/pkg/controllers/subscriptions.go +++ b/pkg/controllers/subscriptions.go @@ -29,7 +29,7 @@ func (wc *SubscriptionController) New(c *gin.Context) { return } - wm := wc.SubscriptionService.New(body) + wm := wc.SubscriptionService.New(c, body) c.JSON(200, wm) } @@ -41,7 +41,7 @@ func (wc *SubscriptionController) GetAll(c *gin.Context) { fr := FilteredResponse(c) wallet, _ := c.GetQuery("walletId") - wc.SubscriptionService.GetAll(body, wallet, fr) + wc.SubscriptionService.GetAll(c, body, wallet, fr) c.JSON(200, fr) } diff --git a/pkg/controllers/transactionTypes.go b/pkg/controllers/transactionTypes.go index ce14351..f8d7288 100644 --- a/pkg/controllers/transactionTypes.go +++ b/pkg/controllers/transactionTypes.go @@ -29,14 +29,14 @@ func (wc *TransactionTypeController) New(c *gin.Context) { return } - wm := wc.TransactionTypeService.New(body) + wm := wc.TransactionTypeService.New(c, body) c.JSON(200, wm) } func (wc *TransactionTypeController) GetAll(c *gin.Context) { embed, _ := c.GetQuery("embed") - wm := wc.TransactionTypeService.GetAll(embed) + wm := wc.TransactionTypeService.GetAll(c, embed) c.JSON(200, wm) } diff --git a/pkg/controllers/transactions.go b/pkg/controllers/transactions.go index 3721c98..b800691 100644 --- a/pkg/controllers/transactions.go +++ b/pkg/controllers/transactions.go @@ -29,7 +29,7 @@ func (wc *TransactionController) New(c *gin.Context) { return } - wm := wc.TransactionService.New(body) + wm := wc.TransactionService.New(c, body) c.JSON(200, wm) } @@ -41,7 +41,7 @@ func (wc *TransactionController) GetAll(c *gin.Context) { fr := FilteredResponse(c) wallet, _ := c.GetQuery("walletId") - wc.TransactionService.GetAll(body, wallet, fr) + wc.TransactionService.GetAll(c, body, wallet, fr) c.JSON(200, fr) } diff --git a/pkg/controllers/wallets-header.go b/pkg/controllers/wallets-header.go index 9bb8cdc..638dbf4 100644 --- a/pkg/controllers/wallets-header.go +++ b/pkg/controllers/wallets-header.go @@ -28,7 +28,7 @@ func (wc *WalletsHeaderController) Get(c *gin.Context) { auth := c.MustGet("auth") body.Id = auth.(*models.Auth).Id - wm := wc.WalletService.GetHeader(body, walletId) + wm := wc.WalletService.GetHeader(c, body, walletId) c.JSON(200, wm) } diff --git a/pkg/controllers/wallets.go b/pkg/controllers/wallets.go index 7ca4e53..62c266f 100644 --- a/pkg/controllers/wallets.go +++ b/pkg/controllers/wallets.go @@ -33,7 +33,7 @@ func (wc *WalletsController) New(c *gin.Context) { get := c.MustGet("auth") body.UserID = get.(*models.Auth).Id - wm := wc.WalletService.New(body) + wm := wc.WalletService.New(c, body) c.JSON(200, wm) } @@ -44,7 +44,7 @@ func (wc *WalletsController) Get(c *gin.Context) { auth := c.MustGet("auth") body.Id = auth.(*models.Auth).Id - wm := wc.WalletService.Get(body, embed) + wm := wc.WalletService.Get(c, body, embed) c.JSON(200, wm) } @@ -56,7 +56,7 @@ func (wc *WalletsController) GetAll(c *gin.Context) { fr := FilteredResponse(c) - wc.WalletService.GetAll(body, fr) + wc.WalletService.GetAll(c, body, fr) c.JSON(200, fr) diff --git a/pkg/middleware/secretCode.go b/pkg/middleware/secretCode.go index 304fb39..e74ca07 100644 --- a/pkg/middleware/secretCode.go +++ b/pkg/middleware/secretCode.go @@ -16,24 +16,26 @@ func SecretCode(c *gin.Context) { if secret == "" { secret = configs.SecretCode } - if secret != secretCode { + if secret != secretCode.SecretCode { exceptionReturn.ErrorCode = "401101" exceptionReturn.StatusCode = 401 exceptionReturn.Message = "Invalid secret code" c.AbortWithStatusJSON(exceptionReturn.StatusCode, exceptionReturn) } + c.Set("migrate", secretCode) c.Next() } -func ExtractCode(c *gin.Context) string { +func ExtractCode(c *gin.Context) SecretCodeModel { secret := new(SecretCodeModel) if err := c.ShouldBindJSON(&secret); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return "" + return SecretCodeModel{} } - return secret.SecretCode + return *secret } type SecretCodeModel struct { SecretCode string `json:"secretCode"` + Version string `json:"version"` } diff --git a/pkg/migrate/migrations/api.go b/pkg/migrate/1_create_table_api.go similarity index 69% rename from pkg/migrate/migrations/api.go rename to pkg/migrate/1_create_table_api.go index cf4ff3c..a7911f9 100644 --- a/pkg/migrate/migrations/api.go +++ b/pkg/migrate/1_create_table_api.go @@ -1,25 +1,22 @@ -package migrations +package migrate import ( "fmt" + "github.com/go-pg/pg/v10" "log" "wallet-api/pkg/models" - "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" ) -type ApiMigration struct { - Db *pg.DB -} +func CreateTableApi(db pg.DB) error { -func (am *ApiMigration) Create() error { models := []interface{}{ (*models.ApiModel)(nil), } for _, model := range models { - err := am.Db.Model(model).CreateTable(&orm.CreateTableOptions{ + err := db.Model(model).CreateTable(&orm.CreateTableOptions{ IfNotExists: true, }) if err != nil { diff --git a/pkg/migrate/migrations/users.go b/pkg/migrate/2_create_table_users.go similarity index 69% rename from pkg/migrate/migrations/users.go rename to pkg/migrate/2_create_table_users.go index 5d079cb..12e98c6 100644 --- a/pkg/migrate/migrations/users.go +++ b/pkg/migrate/2_create_table_users.go @@ -1,25 +1,22 @@ -package migrations +package migrate import ( "fmt" + "github.com/go-pg/pg/v10" "log" "wallet-api/pkg/models" - "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" ) -type UsersMigration struct { - Db *pg.DB -} -func (am *UsersMigration) Create() error { +func CreateTableUsers(db pg.DB) error { models := []interface{}{ (*models.User)(nil), } for _, model := range models { - err := am.Db.Model(model).CreateTable(&orm.CreateTableOptions{ + err := db.Model(model).CreateTable(&orm.CreateTableOptions{ IfNotExists: true, }) if err != nil { diff --git a/pkg/migrate/migrations/wallets.go b/pkg/migrate/3_create_table_wallets.go similarity index 70% rename from pkg/migrate/migrations/wallets.go rename to pkg/migrate/3_create_table_wallets.go index d425002..8b4b371 100644 --- a/pkg/migrate/migrations/wallets.go +++ b/pkg/migrate/3_create_table_wallets.go @@ -1,25 +1,21 @@ -package migrations +package migrate import ( "fmt" + "github.com/go-pg/pg/v10" "log" "wallet-api/pkg/models" - "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" ) -type WalletsMigration struct { - Db *pg.DB -} - -func (am *WalletsMigration) Create() error { +func CreateTableWallets(db pg.DB) error { models := []interface{}{ (*models.Wallet)(nil), } for _, model := range models { - err := am.Db.Model(model).CreateTable(&orm.CreateTableOptions{ + err := db.Model(model).CreateTable(&orm.CreateTableOptions{ IfNotExists: false, FKConstraints: true, }) diff --git a/pkg/migrate/4_create_table_transaction_types.go b/pkg/migrate/4_create_table_transaction_types.go new file mode 100644 index 0000000..9572421 --- /dev/null +++ b/pkg/migrate/4_create_table_transaction_types.go @@ -0,0 +1,30 @@ +package migrate + +import ( + "fmt" + "github.com/go-pg/pg/v10" + "log" + "wallet-api/pkg/models" + + "github.com/go-pg/pg/v10/orm" +) + +func CreateTableTransactionTypes(db pg.DB) error { + models := []interface{}{ + (*models.TransactionType)(nil), + } + + for _, model := range models { + err := db.Model(model).CreateTable(&orm.CreateTableOptions{ + IfNotExists: false, + FKConstraints: true, + }) + if err != nil { + log.Printf("Error Creating Table: %s", err) + return err + } else { + fmt.Println("Table created successfully") + } + } + return nil +} diff --git a/pkg/migrate/migrations/transactions.go b/pkg/migrate/5_create_table_transactions.go similarity index 69% rename from pkg/migrate/migrations/transactions.go rename to pkg/migrate/5_create_table_transactions.go index e6163c8..09a80e9 100644 --- a/pkg/migrate/migrations/transactions.go +++ b/pkg/migrate/5_create_table_transactions.go @@ -1,25 +1,22 @@ -package migrations +package migrate import ( "fmt" + "github.com/go-pg/pg/v10" "log" "wallet-api/pkg/models" - "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" ) -type TransactionsMigration struct { - Db *pg.DB -} -func (am *TransactionsMigration) Create() error { +func CreateTableTransactions(db pg.DB) error { models := []interface{}{ (*models.Transaction)(nil), } for _, model := range models { - err := am.Db.Model(model).CreateTable(&orm.CreateTableOptions{ + err := db.Model(model).CreateTable(&orm.CreateTableOptions{ IfNotExists: false, FKConstraints: true, }) diff --git a/pkg/migrate/6_create_table_subscription_types.go b/pkg/migrate/6_create_table_subscription_types.go new file mode 100644 index 0000000..c2fe7a1 --- /dev/null +++ b/pkg/migrate/6_create_table_subscription_types.go @@ -0,0 +1,30 @@ +package migrate + +import ( + "fmt" + "github.com/go-pg/pg/v10" + "log" + "wallet-api/pkg/models" + + "github.com/go-pg/pg/v10/orm" +) + +func CreateTableSubscriptionTypes(db pg.DB) error { + models := []interface{}{ + (*models.SubscriptionType)(nil), + } + + for _, model := range models { + err := db.Model(model).CreateTable(&orm.CreateTableOptions{ + IfNotExists: false, + FKConstraints: true, + }) + if err != nil { + log.Printf("Error Creating Table: %s", err) + return err + } else { + fmt.Println("Table created successfully") + } + } + return nil +} diff --git a/pkg/migrate/migrations/subscriptions.go b/pkg/migrate/7_create_table_subscriptions.go similarity index 68% rename from pkg/migrate/migrations/subscriptions.go rename to pkg/migrate/7_create_table_subscriptions.go index f7e73c8..6515fd4 100644 --- a/pkg/migrate/migrations/subscriptions.go +++ b/pkg/migrate/7_create_table_subscriptions.go @@ -1,25 +1,20 @@ -package migrations +package migrate import ( "fmt" - "log" - "wallet-api/pkg/models" - "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" + "log" + "wallet-api/pkg/models" ) -type SubscriptionsMigration struct { - Db *pg.DB -} - -func (am *SubscriptionsMigration) Create() error { +func CreateTableSubscriptions(db pg.DB) error { models := []interface{}{ (*models.Subscription)(nil), } for _, model := range models { - err := am.Db.Model(model).CreateTable(&orm.CreateTableOptions{ + err := db.Model(model).CreateTable(&orm.CreateTableOptions{ IfNotExists: false, FKConstraints: true, }) diff --git a/pkg/migrate/8_populate_subscription_types.go b/pkg/migrate/8_populate_subscription_types.go new file mode 100644 index 0000000..1c4d594 --- /dev/null +++ b/pkg/migrate/8_populate_subscription_types.go @@ -0,0 +1,39 @@ +package migrate + +import ( + "github.com/go-pg/pg/v10" + "wallet-api/pkg/models" +) + +func PopulateSubscriptionTypes(db pg.DB) error { + daily := new(models.SubscriptionType) + weekly := new(models.SubscriptionType) + monthly := new(models.SubscriptionType) + yearly := new(models.SubscriptionType) + + daily.Init() + daily.Name = "Daily" + daily.Type = "daily" + + weekly.Init() + weekly.Name = "Weekly" + weekly.Type = "weekly" + + monthly.Init() + monthly.Name = "Monthly" + monthly.Type = "monthly" + + yearly.Init() + yearly.Name = "Yearly" + yearly.Type = "yearly" + + _, err := db.Model(daily).Where("? = ?", pg.Ident("type"), daily.Type).SelectOrInsert() + + _, err = db.Model(weekly).Where("? = ?", pg.Ident("type"), weekly.Type).SelectOrInsert() + + _, err = db.Model(monthly).Where("? = ?", pg.Ident("type"), monthly.Type).SelectOrInsert() + + _, err = db.Model(yearly).Where("? = ?", pg.Ident("type"), yearly.Type).SelectOrInsert() + + return err +} diff --git a/pkg/migrate/9_populate_transaction_types.go b/pkg/migrate/9_populate_transaction_types.go new file mode 100644 index 0000000..4a8b2d5 --- /dev/null +++ b/pkg/migrate/9_populate_transaction_types.go @@ -0,0 +1,25 @@ +package migrate + +import ( + "github.com/go-pg/pg/v10" + "wallet-api/pkg/models" +) + +func PopulateTransactionTypes(db pg.DB) error { + gain := new(models.TransactionType) + expense := new(models.TransactionType) + + gain.Init() + gain.Name = "Gain" + gain.Type = "gain" + + expense.Init() + expense.Name = "Expense" + expense.Type = "expense" + + _, err := db.Model(gain).Where("? = ?", pg.Ident("type"), gain.Type).SelectOrInsert() + + _, err = db.Model(expense).Where("? = ?", pg.Ident("type"), expense.Type).SelectOrInsert() + + return err +} diff --git a/pkg/migrate/migrate.go b/pkg/migrate/migrate.go index 5c35cf7..005d57f 100644 --- a/pkg/migrate/migrate.go +++ b/pkg/migrate/migrate.go @@ -1,30 +1,49 @@ package migrate import ( - "wallet-api/pkg/migrate/migrations" - "github.com/go-pg/pg/v10" ) -func Start(conn *pg.DB) error { - apiMigration := migrations.ApiMigration{Db: conn} - usersMigration := migrations.UsersMigration{Db: conn} - walletsMigration := migrations.WalletsMigration{Db: conn} - transactionTypesMigration := migrations.TransactionTypesMigration{Db: conn} - transactionsMigration := migrations.TransactionsMigration{Db: conn} - subscriptionTypesMigration := migrations.SubscriptionTypesMigration{Db: conn} - subscriptionsMigration := migrations.SubscriptionsMigration{Db: conn} +func Start(conn *pg.DB, version string) { + migration001 := Migration{ + Version: "001", + Migrations: []interface{}{ + CreateTableApi, + CreateTableUsers, + CreateTableWallets, + CreateTableTransactionTypes, + CreateTableTransactions, + CreateTableSubscriptionTypes, + CreateTableSubscriptions, + }, + } + migration002 := Migration{ + Version: "002", + Migrations: []interface{}{ + PopulateSubscriptionTypes, + PopulateTransactionTypes, + }, + } - err := apiMigration.Create() - err = usersMigration.Create() - err = walletsMigration.Create() - err = transactionTypesMigration.Create() - err = subscriptionTypesMigration.Create() - err = subscriptionsMigration.Create() - err = transactionsMigration.Create() + migrationsMap := []Migration{ + migration001, + migration002, + } - err = subscriptionTypesMigration.Populate() - err = transactionTypesMigration.Populate() - - return err + for _, migrationCol := range migrationsMap { + if version != "" && version == migrationCol.Version || version == "" { + for _, migration := range migrationCol.Migrations { + mgFunc, isFunc := migration.(func(pg.DB) error) + if isFunc { + mgFunc(*conn) + } + } + } + } } + +type Migration struct { + Version string + Migrations []interface{} +} + diff --git a/pkg/migrate/migrations/subscriptionTypes.go b/pkg/migrate/migrations/subscriptionTypes.go deleted file mode 100644 index 670d7f1..0000000 --- a/pkg/migrate/migrations/subscriptionTypes.go +++ /dev/null @@ -1,67 +0,0 @@ -package migrations - -import ( - "fmt" - "log" - "wallet-api/pkg/models" - - "github.com/go-pg/pg/v10" - "github.com/go-pg/pg/v10/orm" -) - -type SubscriptionTypesMigration struct { - Db *pg.DB -} - -func (am *SubscriptionTypesMigration) Create() error { - models := []interface{}{ - (*models.SubscriptionType)(nil), - } - - for _, model := range models { - err := am.Db.Model(model).CreateTable(&orm.CreateTableOptions{ - IfNotExists: false, - FKConstraints: true, - }) - if err != nil { - log.Printf("Error Creating Table: %s", err) - return err - } else { - fmt.Println("Table created successfully") - } - } - return nil -} - -func (am *SubscriptionTypesMigration) Populate() error { - daily := new(models.SubscriptionType) - weekly := new(models.SubscriptionType) - monthly := new(models.SubscriptionType) - yearly := new(models.SubscriptionType) - - daily.Init() - daily.Name = "Daily" - daily.Type = "daily" - - weekly.Init() - weekly.Name = "Weekly" - weekly.Type = "weekly" - - monthly.Init() - monthly.Name = "Monthly" - monthly.Type = "monthly" - - yearly.Init() - yearly.Name = "Yearly" - yearly.Type = "yearly" - - _, err := am.Db.Model(daily).Where("? = ?", pg.Ident("type"), daily.Type).SelectOrInsert() - - _, err = am.Db.Model(weekly).Where("? = ?", pg.Ident("type"), weekly.Type).SelectOrInsert() - - _, err = am.Db.Model(monthly).Where("? = ?", pg.Ident("type"), monthly.Type).SelectOrInsert() - - _, err = am.Db.Model(yearly).Where("? = ?", pg.Ident("type"), yearly.Type).SelectOrInsert() - - return err -} diff --git a/pkg/migrate/migrations/transactionTypes.go b/pkg/migrate/migrations/transactionTypes.go deleted file mode 100644 index 714e76b..0000000 --- a/pkg/migrate/migrations/transactionTypes.go +++ /dev/null @@ -1,53 +0,0 @@ -package migrations - -import ( - "fmt" - "log" - "wallet-api/pkg/models" - - "github.com/go-pg/pg/v10" - "github.com/go-pg/pg/v10/orm" -) - -type TransactionTypesMigration struct { - Db *pg.DB -} - -func (am *TransactionTypesMigration) Create() error { - models := []interface{}{ - (*models.TransactionType)(nil), - } - - for _, model := range models { - err := am.Db.Model(model).CreateTable(&orm.CreateTableOptions{ - IfNotExists: false, - FKConstraints: true, - }) - if err != nil { - log.Printf("Error Creating Table: %s", err) - return err - } else { - fmt.Println("Table created successfully") - } - } - return nil -} - -func (am *TransactionTypesMigration) Populate() error { - gain := new(models.TransactionType) - expense := new(models.TransactionType) - - gain.Init() - gain.Name = "Gain" - gain.Type = "gain" - - expense.Init() - expense.Name = "Expense" - expense.Type = "expense" - - _, err := am.Db.Model(gain).Where("? = ?", pg.Ident("type"), gain.Type).SelectOrInsert() - - _, err = am.Db.Model(expense).Where("? = ?", pg.Ident("type"), expense.Type).SelectOrInsert() - - return err -} diff --git a/pkg/services/api.go b/pkg/services/api.go index 77f8b5c..37836f9 100644 --- a/pkg/services/api.go +++ b/pkg/services/api.go @@ -1,6 +1,7 @@ package services import ( + "context" "wallet-api/pkg/migrate" "wallet-api/pkg/models" @@ -11,22 +12,21 @@ type ApiService struct { Db *pg.DB } -func (as *ApiService) GetFirst() models.ApiModel { +func (as *ApiService) GetFirst(ctx context.Context) models.ApiModel { + db := as.Db.WithContext(ctx) + apiModel := models.ApiModel{Api: "Works"} - as.Db.Model(&apiModel).First() + db.Model(&apiModel).First() return apiModel } -func (as *ApiService) PostMigrate() (*models.MessageResponse, *models.Exception) { +func (as *ApiService) PostMigrate(ctx context.Context, version string) (*models.MessageResponse, *models.Exception) { + db := as.Db.WithContext(ctx) + mr := new(models.MessageResponse) er := new(models.Exception) - err := migrate.Start(as.Db) - if err != nil { - er.ErrorCode = "400999" - er.StatusCode = 400 - er.Message = err.Error() - } + migrate.Start(db, version) return mr, er } diff --git a/pkg/services/subscriptionTypes.go b/pkg/services/subscriptionTypes.go index 3a1a1d1..8bb50d6 100644 --- a/pkg/services/subscriptionTypes.go +++ b/pkg/services/subscriptionTypes.go @@ -1,6 +1,7 @@ package services import ( + "context" "wallet-api/pkg/models" "wallet-api/pkg/utl/common" @@ -11,22 +12,26 @@ type SubscriptionTypeService struct { Db *pg.DB } -func (as *SubscriptionTypeService) New(body *models.NewSubscriptionTypeBody) *models.SubscriptionType { +func (as *SubscriptionTypeService) New(ctx context.Context, body *models.NewSubscriptionTypeBody) *models.SubscriptionType { + db := as.Db.WithContext(ctx) + tm := new(models.SubscriptionType) tm.Init() tm.Name = body.Name tm.Type = body.Type - as.Db.Model(tm).Insert() + db.Model(tm).Insert() return tm } -func (as *SubscriptionTypeService) GetAll(embed string) *[]models.SubscriptionType { +func (as *SubscriptionTypeService) GetAll(ctx context.Context, embed string) *[]models.SubscriptionType { + db := as.Db.WithContext(ctx) + wm := new([]models.SubscriptionType) - query := as.Db.Model(wm) + query := db.Model(wm) common.GenerateEmbed(query, embed).Select() return wm diff --git a/pkg/services/subscriptions.go b/pkg/services/subscriptions.go index 1db9553..601771b 100644 --- a/pkg/services/subscriptions.go +++ b/pkg/services/subscriptions.go @@ -1,6 +1,7 @@ package services import ( + "context" "math" "time" "wallet-api/pkg/models" @@ -12,7 +13,9 @@ type SubscriptionService struct { Db *pg.DB } -func (as *SubscriptionService) New(body *models.NewSubscriptionBody) *models.Subscription { +func (as *SubscriptionService) New(ctx context.Context, body *models.NewSubscriptionBody) *models.Subscription { + db := as.Db.WithContext(ctx) + tm := new(models.Subscription) amount, _ := body.Amount.Float64() @@ -33,7 +36,7 @@ func (as *SubscriptionService) New(body *models.NewSubscriptionBody) *models.Sub tm.StartDate = time.Now() } - tx, _ := as.Db.Begin() + tx, _ := db.Begin() defer tx.Rollback() tx.Model(tm).Insert() @@ -44,10 +47,12 @@ func (as *SubscriptionService) New(body *models.NewSubscriptionBody) *models.Sub return tm } -func (as *SubscriptionService) GetAll(am *models.Auth, walletId string, filtered *models.FilteredResponse) { +func (as *SubscriptionService) GetAll(ctx context.Context, am *models.Auth, walletId string, filtered *models.FilteredResponse) { + db := as.Db.WithContext(ctx) + wm := new([]models.Subscription) - tx, _ := as.Db.Begin() + tx, _ := db.Begin() defer tx.Rollback() query := tx.Model(wm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) diff --git a/pkg/services/transactionTypes.go b/pkg/services/transactionTypes.go index dcaa2c9..eff9696 100644 --- a/pkg/services/transactionTypes.go +++ b/pkg/services/transactionTypes.go @@ -1,6 +1,7 @@ package services import ( + "context" "wallet-api/pkg/models" "wallet-api/pkg/utl/common" @@ -11,22 +12,26 @@ type TransactionTypeService struct { Db *pg.DB } -func (as *TransactionTypeService) New(body *models.NewTransactionTypeBody) *models.TransactionType { +func (as *TransactionTypeService) New(ctx context.Context, body *models.NewTransactionTypeBody) *models.TransactionType { + db := as.Db.WithContext(ctx) + tm := new(models.TransactionType) tm.Init() tm.Name = body.Name tm.Type = body.Type - as.Db.Model(tm).Insert() + db.Model(tm).Insert() return tm } -func (as *TransactionTypeService) GetAll(embed string) *[]models.TransactionType { +func (as *TransactionTypeService) GetAll(ctx context.Context, embed string) *[]models.TransactionType { + db := as.Db.WithContext(ctx) + wm := new([]models.TransactionType) - query := as.Db.Model(wm) + query := db.Model(wm) common.GenerateEmbed(query, embed).Select() return wm diff --git a/pkg/services/transactions.go b/pkg/services/transactions.go index d11015a..a7406af 100644 --- a/pkg/services/transactions.go +++ b/pkg/services/transactions.go @@ -1,6 +1,7 @@ package services import ( + "context" "math" "time" "wallet-api/pkg/models" @@ -13,7 +14,9 @@ type TransactionService struct { Ss *SubscriptionService } -func (as *TransactionService) New(body *models.NewTransactionBody) *models.Transaction { +func (as *TransactionService) New(ctx context.Context, body *models.NewTransactionBody) *models.Transaction { + db := as.Db.WithContext(ctx) + tm := new(models.Transaction) amount, _ := body.Amount.Float64() @@ -29,16 +32,18 @@ func (as *TransactionService) New(body *models.NewTransactionBody) *models.Trans tm.TransactionDate = time.Now() } - as.Db.Model(tm).Insert() + db.Model(tm).Insert() return tm } -func (as *TransactionService) GetAll(am *models.Auth, walletId string, filtered *models.FilteredResponse) { +func (as *TransactionService) GetAll(ctx context.Context, am *models.Auth, walletId string, filtered *models.FilteredResponse) { + db := as.Db.WithContext(ctx) + wm := new([]models.Transaction) sm := new([]models.Subscription) - tx, _ := as.Db.Begin() + tx, _ := db.Begin() defer tx.Rollback() query2 := tx.Model(sm).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id) diff --git a/pkg/services/users.go b/pkg/services/users.go index 04edcec..608a93c 100644 --- a/pkg/services/users.go +++ b/pkg/services/users.go @@ -1,6 +1,7 @@ package services import ( + "context" "os" "time" "wallet-api/pkg/models" @@ -17,11 +18,13 @@ type UsersService struct { Db *pg.DB } -func (us *UsersService) Create(registerBody *models.User) (*models.User, *models.Exception) { +func (us *UsersService) Create(ctx context.Context, registerBody *models.User) (*models.User, *models.Exception) { + db := us.Db.WithContext(ctx) + check := new(models.User) exceptionReturn := new(models.Exception) - tx, _ := us.Db.Begin() + tx, _ := db.Begin() defer tx.Rollback() tx.Model(check).Where("? = ?", pg.Ident("username"), registerBody.Username).WhereOr("? = ?", pg.Ident("email"), registerBody.Email).Select() @@ -49,12 +52,14 @@ func (us *UsersService) Create(registerBody *models.User) (*models.User, *models return registerBody, exceptionReturn } -func (us *UsersService) Login(loginBody *models.Login) (*models.Token, *models.Exception) { +func (us *UsersService) Login(ctx context.Context, loginBody *models.Login) (*models.Token, *models.Exception) { + db := us.Db.WithContext(ctx) + check := new(models.User) exceptionReturn := new(models.Exception) tokenPayload := new(models.Token) - us.Db.Model(check).Where("? = ?", pg.Ident("email"), loginBody.Email).Select() + db.Model(check).Where("? = ?", pg.Ident("email"), loginBody.Email).Select() if check.Email == "" { exceptionReturn.Message = "Email not found" exceptionReturn.ErrorCode = "400103" @@ -84,12 +89,14 @@ func (us *UsersService) Login(loginBody *models.Login) (*models.Token, *models.E return tokenPayload, exceptionReturn } -func (us *UsersService) Deactivate(auth *models.Auth) (*models.MessageResponse, *models.Exception) { +func (us *UsersService) Deactivate(ctx context.Context, auth *models.Auth) (*models.MessageResponse, *models.Exception) { + db := us.Db.WithContext(ctx) + mm := new(models.MessageResponse) me := new(models.Exception) um := new(models.User) - tx, _ := us.Db.Begin() + tx, _ := db.Begin() defer tx.Rollback() err := tx.Model(um).Where("? = ?", pg.Ident("id"), auth.Id).Select() diff --git a/pkg/services/wallets.go b/pkg/services/wallets.go index 462eb92..7bb9e59 100644 --- a/pkg/services/wallets.go +++ b/pkg/services/wallets.go @@ -1,6 +1,7 @@ package services import ( + "context" "sync" "time" "wallet-api/pkg/models" @@ -14,40 +15,46 @@ type WalletService struct { Ss *SubscriptionService } -func (as *WalletService) New(am *models.NewWalletBody) *models.Wallet { +func (as *WalletService) New(ctx context.Context, am *models.NewWalletBody) *models.Wallet { + db := as.Db.WithContext(ctx) walletModel := new(models.Wallet) walletModel.Init() walletModel.UserID = am.UserID walletModel.Name = am.Name - as.Db.Model(walletModel).Insert() + db.Model(walletModel).Insert() return walletModel } -func (as *WalletService) Get(am *models.Auth, embed string) *models.Wallet { +func (as *WalletService) Get(ctx context.Context, am *models.Auth, embed string) *models.Wallet { + db := as.Db.WithContext(ctx) + wm := new(models.Wallet) - query := as.Db.Model(wm).Where("? = ?", pg.Ident("user_id"), am.Id) + query := db.Model(wm).Where("? = ?", pg.Ident("user_id"), am.Id) common.GenerateEmbed(query, embed).Select() return wm } -func (as *WalletService) GetAll(am *models.Auth, filtered *models.FilteredResponse) { +func (as *WalletService) GetAll(ctx context.Context, am *models.Auth, filtered *models.FilteredResponse) { + db := as.Db.WithContext(ctx) wm := new([]models.Wallet) - query := as.Db.Model(wm).Where("? = ?", pg.Ident("user_id"), am.Id) + query := db.Model(wm).Where("? = ?", pg.Ident("user_id"), am.Id) FilteredResponse(query, wm, filtered) } -func (as *WalletService) GetHeader(am *models.Auth, walletId string) *models.WalletHeader { +func (as *WalletService) GetHeader(ctx context.Context, am *models.Auth, walletId string) *models.WalletHeader { + db := as.Db.WithContext(ctx) + wm := new(models.WalletHeader) wallets := new([]models.WalletTransactions) var wg sync.WaitGroup transactions := new([]models.Transaction) subscriptions := new([]models.Subscription) - tx, _ := as.Db.Begin() + tx, _ := db.Begin() defer tx.Rollback() query2 := tx.Model(subscriptions).Relation("Wallet").Where("wallet.? = ?", pg.Ident("user_id"), am.Id).Relation("TransactionType").Relation("SubscriptionType") @@ -83,22 +90,22 @@ func (as *WalletService) GetHeader(am *models.Auth, walletId string) *models.Wal for i, wallet := range *wallets { for _, trans := range wallet.Transactions { - tzFirstOfMonthAfterNext := firstOfMonthAfterNext.In(trans.TransactionDate.Location()) - tzFirstOfNextMonth := firstOfNextMonth.In(trans.TransactionDate.Location()) - tzFirstOfMonth := firstOfMonth.In(trans.TransactionDate.Location()) - if trans.TransactionDate.Before(tzFirstOfNextMonth) && trans.TransactionDate.After(tzFirstOfMonth) || trans.TransactionDate.Equal(tzFirstOfMonth) { + // tzFirstOfMonthAfterNext := firstOfMonthAfterNext.In(trans.TransactionDate.Location()) + // tzFirstOfNextMonth := firstOfNextMonth.In(trans.TransactionDate.Location()) + // tzFirstOfMonth := firstOfMonth.In(trans.TransactionDate.Location()) + if trans.TransactionDate.Before(firstOfMonth) && trans.TransactionDate.After(firstOfMonth) || trans.TransactionDate.Equal(firstOfMonth) { if trans.TransactionType.Type == "expense" { (*wallets)[i].CurrentBalance -= trans.Amount } else { (*wallets)[i].CurrentBalance += trans.Amount } - } else if trans.TransactionDate.Before(tzFirstOfMonthAfterNext) && trans.TransactionDate.After(tzFirstOfNextMonth) { + } else if trans.TransactionDate.Before(firstOfMonthAfterNext) && trans.TransactionDate.After(firstOfNextMonth) { if trans.TransactionType.Type == "expense" { (*wallets)[i].NextMonth -= trans.Amount } else { (*wallets)[i].NextMonth += trans.Amount } - } else if trans.TransactionDate.Before(tzFirstOfMonth) { + } else if trans.TransactionDate.Before(firstOfMonth) { if trans.TransactionType.Type == "expense" { (*wallets)[i].LastMonth -= trans.Amount } else { diff --git a/pkg/utl/db/db.go b/pkg/utl/db/db.go index 66c1b8f..3a2de59 100644 --- a/pkg/utl/db/db.go +++ b/pkg/utl/db/db.go @@ -1,17 +1,19 @@ package db import ( + "context" "fmt" "wallet-api/pkg/utl/common" "github.com/go-pg/pg/v10" ) -func CreateConnection(dbUrl string) *pg.DB { +func CreateConnection(dbUrl string, ctx context.Context) *pg.DB { opt, err := pg.ParseURL(dbUrl) common.CheckError(err) conn := pg.Connect(opt) + db := conn.WithContext(ctx) fmt.Println("Successfully connected!") - return conn + return db }