Set stores data in the cache.
(key string, data interface{}, ttl time.Duration)
| 203 | |
| 204 | // Set stores data in the cache. |
| 205 | func (c *BadgerCache) Set(key string, data interface{}, ttl time.Duration) error { |
| 206 | // Marshal data to JSON once (avoids double marshaling on Get) |
| 207 | jsonData, err := json.Marshal(data) |
| 208 | if err != nil { |
| 209 | return fmt.Errorf("marshal data: %w", err) |
| 210 | } |
| 211 | |
| 212 | // Create cache item with pre-marshaled JSON |
| 213 | item := &CacheItem{ |
| 214 | Data: jsonData, |
| 215 | Timestamp: time.Now().Unix(), |
| 216 | TTL: int64(ttl.Seconds()), |
| 217 | } |
| 218 | |
| 219 | // Convert cache item to JSON |
| 220 | bytes, err := json.Marshal(item) |
| 221 | if err != nil { |
| 222 | return fmt.Errorf("marshal cache item: %w", err) |
| 223 | } |
| 224 | |
| 225 | // Store in Badger |
| 226 | err = c.db.Update(func(txn *badger.Txn) error { |
| 227 | return txn.Set([]byte(key), bytes) |
| 228 | }) |
| 229 | if err != nil { |
| 230 | return fmt.Errorf("badger set operation: %w", err) |
| 231 | } |
| 232 | |
| 233 | getCacheLogger().Debug("Cached item: %s with TTL %v", key, ttl) |
| 234 | |
| 235 | return nil |
| 236 | } |
| 237 | |
| 238 | // Delete removes an item from the cache. |
| 239 | func (c *BadgerCache) Delete(key string) error { |