2022-04-29 13:02:25 -07:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2023-01-22 10:12:55 -08:00
|
|
|
"github.com/jtom38/newsbot/collector/domain/models"
|
2022-04-29 13:02:25 -07:00
|
|
|
)
|
|
|
|
|
2022-12-04 08:49:17 -08:00
|
|
|
type CacheClient struct {
|
|
|
|
group string
|
2022-04-29 13:02:25 -07:00
|
|
|
DefaultTimer time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCacheClient(group string) CacheClient {
|
|
|
|
return CacheClient{
|
2022-12-04 08:49:17 -08:00
|
|
|
group: group,
|
2022-04-29 13:02:25 -07:00
|
|
|
DefaultTimer: time.Hour,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cc *CacheClient) Insert(key string, value string) {
|
2023-01-22 10:12:55 -08:00
|
|
|
item := models.CacheItem{
|
2022-12-04 08:49:17 -08:00
|
|
|
Key: key,
|
|
|
|
Value: value,
|
|
|
|
Group: cc.group,
|
|
|
|
Expires: time.Now().Add(1 * time.Hour),
|
2022-04-29 13:02:25 -07:00
|
|
|
IsTainted: false,
|
|
|
|
}
|
|
|
|
cacheStorage = append(cacheStorage, &item)
|
|
|
|
}
|
|
|
|
|
2023-01-22 10:12:55 -08:00
|
|
|
func (cc *CacheClient) FindByKey(key string) (*models.CacheItem, error) {
|
2022-04-29 13:02:25 -07:00
|
|
|
for _, item := range cacheStorage {
|
2022-12-04 08:49:17 -08:00
|
|
|
if item.Group != cc.group {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if item.Key != key {
|
|
|
|
continue
|
|
|
|
}
|
2022-04-29 13:02:25 -07:00
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2023-01-22 10:12:55 -08:00
|
|
|
return &models.CacheItem{}, ErrCacheRecordMissing
|
2022-04-29 13:02:25 -07:00
|
|
|
}
|
|
|
|
|
2023-01-22 10:12:55 -08:00
|
|
|
func (cc *CacheClient) FindByValue(value string) (*models.CacheItem, error) {
|
2022-04-29 13:02:25 -07:00
|
|
|
for _, item := range cacheStorage {
|
2022-12-04 08:49:17 -08:00
|
|
|
if item.Group != cc.group {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if item.Value != value {
|
|
|
|
continue
|
|
|
|
}
|
2022-04-29 13:02:25 -07:00
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
2023-01-22 10:12:55 -08:00
|
|
|
return &models.CacheItem{}, ErrCacheRecordMissing
|
2022-04-29 13:02:25 -07:00
|
|
|
}
|