upgraded migrations and context usage

This commit is contained in:
Fran Jurmanović
2021-07-03 00:01:25 +02:00
parent 4189a0d333
commit 788ff3a146
33 changed files with 321 additions and 251 deletions

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)
}

View File

@@ -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)
}

View File

@@ -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)
}

View File

@@ -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)
}

View File

@@ -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)
}

View File

@@ -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)

View File

@@ -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"`
}

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -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,
})

View File

@@ -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
}

View File

@@ -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,
})

View File

@@ -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
}

View File

@@ -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,
})

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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{}
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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

View File

@@ -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)

View File

@@ -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

View File

@@ -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)

View File

@@ -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()

View File

@@ -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 {

View File

@@ -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
}