Skip to content

Commit

Permalink
get cache ttl from config
Browse files Browse the repository at this point in the history
  • Loading branch information
gusin13 committed Dec 3, 2024
1 parent 09f7d77 commit b710138
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
11 changes: 8 additions & 3 deletions internal/config/external_apis.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ type ExternalAPIsConfig struct {
}

type CoinMarketCapConfig struct {
APIKey string `mapstructure:"api_key"`
BaseURL string `mapstructure:"base_url"`
Timeout time.Duration `mapstructure:"timeout"`
APIKey string `mapstructure:"api_key"`
BaseURL string `mapstructure:"base_url"`
Timeout time.Duration `mapstructure:"timeout"`
CacheTTL time.Duration `mapstructure:"cache_ttl"`
}

func (cfg *ExternalAPIsConfig) Validate() error {
Expand Down Expand Up @@ -40,5 +41,9 @@ func (cfg *CoinMarketCapConfig) Validate() error {
return fmt.Errorf("invalid coinmarketcap timeout")
}

if cfg.CacheTTL <= 0 {
return fmt.Errorf("invalid coinmarketcap cache ttl")
}

return nil
}
6 changes: 3 additions & 3 deletions internal/db/model/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func Setup(ctx context.Context, cfg *config.Config) error {
}

// Create TTL index for BTC price collection
if err := createTTLIndexes(ctx, database); err != nil {
if err := createTTLIndexes(ctx, database, cfg.ExternalAPIs.CoinMarketCap.CacheTTL); err != nil {
log.Error().Err(err).Msg("Failed to create TTL index for BTC price")
return err
}
Expand Down Expand Up @@ -131,13 +131,13 @@ func createIndex(ctx context.Context, database *mongo.Database, collectionName s
log.Debug().Msg("Index created successfully on collection: " + collectionName)
}

func createTTLIndexes(ctx context.Context, database *mongo.Database) error {
func createTTLIndexes(ctx context.Context, database *mongo.Database, cacheTTL time.Duration) error {
collection := database.Collection(BtcPriceCollection)

// Create TTL index with expiration
index := mongo.IndexModel{
Keys: bson.D{{Key: "created_at", Value: 1}},
Options: options.Index().SetExpireAfterSeconds(3), // 5 minutes TTL
Options: options.Index().SetExpireAfterSeconds(int32(cacheTTL.Seconds())), // TTL from config
}

_, err := collection.Indexes().CreateOne(ctx, index)
Expand Down

0 comments on commit b710138

Please sign in to comment.