tests: cache
This commit is contained in:
parent
92732f9682
commit
597feb7b54
8 changed files with 822 additions and 32 deletions
37
cache/memory.go
vendored
37
cache/memory.go
vendored
|
@ -10,30 +10,44 @@ import (
|
|||
var _ model.Cache = (*MemoryCache)(nil)
|
||||
|
||||
type MemoryCache struct {
|
||||
data map[string]any
|
||||
data map[string]model.CacheItem
|
||||
dataMu sync.RWMutex
|
||||
}
|
||||
|
||||
func (c *MemoryCache) Get(key string) (result any, err error) {
|
||||
c.dataMu.RLock()
|
||||
defer c.dataMu.RUnlock()
|
||||
|
||||
result, exists := c.data[key]
|
||||
item, exists := c.data[key]
|
||||
if !exists {
|
||||
c.dataMu.RUnlock()
|
||||
return result, model.ErrCacheKeyDontExist
|
||||
}
|
||||
|
||||
return
|
||||
// Check expiration while still holding the lock
|
||||
if item.TTL != nil && item.TTL.Before(time.Now()) {
|
||||
c.dataMu.RUnlock()
|
||||
_ = c.Delete(key)
|
||||
return result, model.ErrCacheKeyDontExist
|
||||
}
|
||||
|
||||
value := item.Value
|
||||
c.dataMu.RUnlock()
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (c *MemoryCache) GetWithExpiry(key string, expiration time.Duration) (any, error) {
|
||||
// TODO: Implement expiration in memory cache.
|
||||
return c.Get(key)
|
||||
}
|
||||
func (c *MemoryCache) Set(key string, value any, opts ...model.CacheOption) error {
|
||||
item := model.CacheItem{
|
||||
Key: key,
|
||||
Value: value,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&item)
|
||||
}
|
||||
|
||||
func (c *MemoryCache) Set(key string, value any) error {
|
||||
c.dataMu.Lock()
|
||||
c.data[key] = value
|
||||
c.data[key] = item
|
||||
c.dataMu.Unlock()
|
||||
|
||||
return nil
|
||||
|
@ -48,6 +62,7 @@ func (c *MemoryCache) Delete(key string) error {
|
|||
|
||||
func NewMemoryCache() *MemoryCache {
|
||||
return &MemoryCache{
|
||||
data: make(map[string]any),
|
||||
data: make(map[string]model.CacheItem),
|
||||
dataMu: sync.RWMutex{},
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue