2021-12-30 05:14:18 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
2022-02-28 15:41:56 +00:00
|
|
|
"encoding/json"
|
2021-12-30 05:14:18 +00:00
|
|
|
|
2022-02-28 15:41:56 +00:00
|
|
|
"github.com/mrusme/superhighway84/models"
|
|
|
|
"github.com/tidwall/buntdb"
|
2021-12-30 05:14:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Cache struct {
|
2021-12-30 05:56:51 +00:00
|
|
|
db *buntdb.DB
|
2022-02-28 15:41:56 +00:00
|
|
|
dbPath string
|
2021-12-30 05:14:18 +00:00
|
|
|
}
|
|
|
|
|
2021-12-30 05:56:51 +00:00
|
|
|
func NewCache(dbPath string) (*Cache, error) {
|
2021-12-30 05:14:18 +00:00
|
|
|
var err error
|
|
|
|
|
|
|
|
cache := new(Cache)
|
2022-02-28 15:41:56 +00:00
|
|
|
cache.dbPath = dbPath
|
2021-12-30 05:56:51 +00:00
|
|
|
cache.db, err = buntdb.Open(cache.dbPath)
|
2021-12-30 05:14:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return cache, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func(cache *Cache) Close() {
|
|
|
|
cache.db.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func(cache *Cache) StoreArticle(article *models.Article) (error) {
|
|
|
|
modelJson, jsonErr := json.Marshal(article)
|
|
|
|
if jsonErr != nil {
|
|
|
|
return jsonErr
|
|
|
|
}
|
|
|
|
|
|
|
|
err := cache.db.Update(func(tx *buntdb.Tx) error {
|
|
|
|
_, _, err := tx.Set(article.ID, string(modelJson), nil)
|
|
|
|
return err
|
|
|
|
})
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func(cache *Cache) LoadArticle(article *models.Article) (error) {
|
|
|
|
err := cache.db.View(func(tx *buntdb.Tx) error {
|
|
|
|
value, err := tx.Get(article.ID)
|
|
|
|
if err != nil{
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
json.Unmarshal([]byte(value), article)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|