newsbot-api/internal/services/cache/cache.go

70 lines
1.5 KiB
Go
Raw Permalink Normal View History

package cache
import (
"time"
2024-04-23 07:15:38 -07:00
"git.jamestombleson.com/jtom38/newsbot-api/internal/domain"
)
type CacheClient struct {
group string
DefaultTimer time.Duration
}
func NewCacheClient(group string) CacheClient {
return CacheClient{
group: group,
DefaultTimer: time.Hour,
}
}
func (cc *CacheClient) Insert(key string, value string) {
2024-04-23 07:15:38 -07:00
item := domain.CacheItem{
Key: key,
Value: value,
Group: cc.group,
Expires: time.Now().Add(1 * time.Hour),
IsTainted: false,
}
cacheStorage = append(cacheStorage, &item)
}
2024-04-23 07:15:38 -07:00
func (cc *CacheClient) FindByKey(key string) (*domain.CacheItem, error) {
for _, item := range cacheStorage {
if item.Group != cc.group {
continue
}
if item.Key != key {
continue
}
// if it was tainted, renew the timer and remove the taint as this record was still needed
if item.IsTainted {
item.IsTainted = false
item.Expires = time.Now().Add(1 * time.Hour)
}
return item, nil
}
2024-04-23 07:15:38 -07:00
return &domain.CacheItem{}, ErrCacheRecordMissing
}
2024-04-23 07:15:38 -07:00
func (cc *CacheClient) FindByValue(value string) (*domain.CacheItem, error) {
for _, item := range cacheStorage {
if item.Group != cc.group {
continue
}
if item.Value != value {
continue
}
// if it was tainted, renew the timer and remove the taint as this record was still needed
if item.IsTainted {
item.IsTainted = false
item.Expires = time.Now().Add(1 * time.Hour)
}
return item, nil
}
2024-04-23 07:15:38 -07:00
return &domain.CacheItem{}, ErrCacheRecordMissing
}