Skip to content

Commit

Permalink
Fix bugs in Holding
Browse files Browse the repository at this point in the history
  • Loading branch information
vanshpatelx committed Mar 2, 2025
1 parent 89b842c commit f5a485b
Show file tree
Hide file tree
Showing 24 changed files with 1,138 additions and 207 deletions.
35 changes: 35 additions & 0 deletions backend/holding/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
### JWT Secret
JWT_SECRET=helloworld

### User Database Configuration
USER_DB_HOST=localhost
USER_DB_PORT=5435
USER_DB_USER=admin
USER_DB_PASSWORD=password
USER_DB_NAME=mydatabase

### Holding Database Configuration
HOLDING_DB_HOST=localhost
HOLDING_DB_PORT=5434
HOLDING_DB_USER=admin
HOLDING_DB_PASSWORD=password
HOLDING_DB_NAME=mydatabase

### User Redis Configuration
USER_REDIS_HOST=localhost
USER_REDIS_PORT=6382
USER_REDIS_PASSWORD=password

### Holding Redis Configuration
HOLDING_REDIS_HOST=localhost
HOLDING_REDIS_PORT=6381
HOLDING_REDIS_PASSWORD=password

### RabbitMQ Configuration
RABBITMQ_USER=admin
RABBITMQ_PASSWORD=password
RABBITMQ_HOST=localhost
RABBITMQ_PORT=5672

### Application Port
PORT=8080
35 changes: 34 additions & 1 deletion backend/holding/a.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,37 @@ Holding:UserID:UserID
"price": "100",
"quantity": ""
"locked": ""
}]
}]



========================left work==========================
- Adding balance
Holding DB (2)
Holding Cache (2)
- Middleware Checks
- Adding Dummy table and data

- Function checks
- Write new function => Add Balnace
- test it
=======================================

Test Case:
Get holding means stock avalible
1. Get holding means stock avalible
2. Check user only access their own holdings
3. Admin can access anyone holdings
4. Invalid UserID (Params)
5. Without token
Get Balance
1. Get Balance
2. Check user only access their own balance
3. Admin can access anyone balance
4. Invalid Params (userID, balance)
5. Without token
Update Balance
1. Update Balance
2. Update user only access their own balance
3. Invalid Params (userID, balance)
4. Without token
Binary file added backend/holding/cmd/main
Binary file not shown.
56 changes: 24 additions & 32 deletions backend/holding/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,47 +99,39 @@ import (
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"

"holding/pkg/cache"
"holding/pkg/db"
"holding/pkg/middleware"
"holding/pkg/config"
"holding/pkg/healthcheck"
"holding/pkg/routes"
)

func main() {
app := fiber.New(fiber.Config{
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
config.LoadConfig()

cache.Init("localhost:6379", "")
db.Init("postgres://admin:admin123@localhost:5432/mydatabase?sslmode=disable")
// Check service readiness before proceeding
healthcheck.CheckAllServices()

// Middleware
app.Use(logger.New()) // Log requests
app.Use(cors.New()) // Enable CORS
app := fiber.New(fiber.Config{
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})

app.Post("/auth/login", func(c *fiber.Ctx) error {
// Dummy user data (in real-world, verify username & password)
id := "12334512412334512412"
role := "admin"
// Middleware
app.Use(logger.New()) // Log requests
app.Use(cors.New()) // Enable CORS

token, err := middleware.GenerateJWT(id, role)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to generate token"})
}
return c.JSON(fiber.Map{"token": token})
})
app.Get("/", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"message": "🚀 Holding Service is Running!",
})
})


app.Get("/holding/health", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"success": true, "message": "Server is running."})
})

app.Get("/", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"message": "🚀 Holding Service is Running!"})
})
routes.RegisterHoldingRoutes(app)

app.Get("/holding/health", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"success": true, "message": "Server is running."})
})

routes.RegisterHoldingRoutes(app)

log.Fatal(app.Listen(":3005"))
log.Println("✅ Server is starting on port", config.AppConfig.Port)
app.Listen(":" + config.AppConfig.Port)
}
1 change: 1 addition & 0 deletions backend/holding/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
github.com/goccy/go-json v0.10.5
github.com/gofiber/fiber/v2 v2.52.6
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.10.9
github.com/redis/go-redis/v9 v9.7.1
)
Expand Down
20 changes: 20 additions & 0 deletions backend/holding/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/gofiber/fiber/v2 v2.52.6 h1:Rfp+ILPiYSvvVuIPvxrBns+HJp8qGLDnLJawAu27XVI=
Expand All @@ -16,6 +20,8 @@ github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17w
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
Expand All @@ -27,6 +33,12 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
github.com/redis/go-redis/v9 v9.7.1 h1:4LhKRCIduqXqtvCUlaq9c8bdHOkICjDMrr1+Zb3osAc=
github.com/redis/go-redis/v9 v9.7.1/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
Expand All @@ -39,7 +51,15 @@ github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVS
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
golang.org/x/net v0.31.0 h1:68CPQngjLL0r2AlUKiSxtQFKvzRVbnzLwMUn5SzcLHo=
golang.org/x/net v0.31.0/go.mod h1:P4fl1q7dY2hnZFxEk4pPSkDHF+QqjitcnDjUQyMM+pM=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
7 changes: 7 additions & 0 deletions backend/holding/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "holding",
"scripts": {
"build": "go build -o cmd/main ./cmd",
"dev": "go run cmd/main.go"
}
}
79 changes: 0 additions & 79 deletions backend/holding/pkg/cache/cache.go

This file was deleted.

84 changes: 84 additions & 0 deletions backend/holding/pkg/cache/cacheHolding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package cache

import (
"context"
"encoding/json"
"holding/pkg/config"
"sync"
"time"

"github.com/redis/go-redis/v9"
)

var (
onceHolding sync.Once
redisClientHolding *redis.Client
ctxHolding = context.Background()
)

// Init initializes the Redis client as a singleton
func InitHolding(redisURL, redisPassword string) error {
var initErr error

onceHolding.Do(func() {
redisClientHolding = redis.NewClient(&redis.Options{
Addr: redisURL,
Password: redisPassword,
DB: 0,
})

// Retry connection with exponential backoff
for attempt := 1; attempt <= 5; attempt++ {
_, err := redisClientHolding.Ping(ctxHolding).Result()
if err == nil {
initErr = nil
return
}
initErr = err
time.Sleep(time.Duration(attempt) * 2 * time.Second) // Exponential backoff
}
})

return initErr
}

// GetRedisClient returns the singleton Redis client
func GetRedisClientHolding() *redis.Client {
if redisClientHolding == nil {
InitHolding(config.AppConfig.HOLDING_RedisURL, config.AppConfig.HOLDING_RedisPassword)
}
return redisClientHolding
}

// Get retrieves a value from Redis
func GetHolding(key string) (map[string]interface{}, error) {
val, err := GetRedisClientHolding().Get(ctxHolding, key).Result()
if err != nil {
return nil, err
}

var data map[string]interface{}
err = json.Unmarshal([]byte(val), &data)
if err != nil {
return nil, err
}

return data, nil
}

// Set stores a value in Redis
func SetHolding(key string, value map[string]interface{}, expire time.Duration) error {
jsonValue, err := json.Marshal(value)
if err != nil {
return err
}

return GetRedisClientHolding().Set(ctxHolding, key, jsonValue, expire).Err()
}

// Close closes the Redis connection
func CloseHolding() {
if redisClientHolding != nil {
_ = redisClientHolding.Close()
}
}
Loading

0 comments on commit f5a485b

Please sign in to comment.