@@ -6,8 +6,11 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/patrickmn/go-cache"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Product struct {
|
||||
@@ -30,14 +33,18 @@ var (
|
||||
ErrProductNotFound = errors.New("product not found")
|
||||
)
|
||||
|
||||
type storageFile struct{}
|
||||
type storageFile struct {
|
||||
cache *cache.Cache
|
||||
}
|
||||
|
||||
func NewStorageFile() storage.IStorage {
|
||||
return &storageFile{}
|
||||
return &storageFile{
|
||||
cache: cache.New(24*time.Hour, time.Hour),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *storageFile) GetCatalog(_ context.Context) ([]*crm.Category, error) {
|
||||
data, err := os.ReadFile("resources/catalog.json")
|
||||
data, err := s.readFile("catalog")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -49,7 +56,7 @@ func (s *storageFile) GetCatalog(_ context.Context) ([]*crm.Category, error) {
|
||||
}
|
||||
|
||||
func (s *storageFile) GetPositions(_ context.Context, id int64) ([]*crm.Product, error) {
|
||||
data, err := os.ReadFile("resources/products.json")
|
||||
data, err := s.readFile("products")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -68,7 +75,7 @@ func (s *storageFile) GetPositions(_ context.Context, id int64) ([]*crm.Product,
|
||||
}
|
||||
|
||||
func (s *storageFile) GetProduct(_ context.Context, id int64) (*crm.Product, error) {
|
||||
data, err := os.ReadFile("resources/products.json")
|
||||
data, err := s.readFile("products")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -123,7 +130,7 @@ func (s *storageFile) GetBreadcrumbs(ctx context.Context, id int64) ([]*crm.Cate
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := os.ReadFile("resources/catalog.json")
|
||||
data, err := s.readFile("catalog")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -163,7 +170,7 @@ func getBreadcrumbs(categories []*crm.Category, id int64) []*crm.Category {
|
||||
}
|
||||
|
||||
func (s *storageFile) GetPositionsByText(_ context.Context, text string) ([]*crm.Product, error) {
|
||||
data, err := os.ReadFile("resources/products.json")
|
||||
data, err := s.readFile("products")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -182,3 +189,16 @@ func (s *storageFile) GetPositionsByText(_ context.Context, text string) ([]*crm
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (s *storageFile) readFile(name string) ([]byte, error) {
|
||||
cacheData, found := s.cache.Get(name)
|
||||
if found {
|
||||
return cacheData.([]byte), nil
|
||||
}
|
||||
data, err := os.ReadFile(fmt.Sprintf("resources/%s.json", name))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.cache.Set(name, data, cache.DefaultExpiration)
|
||||
return data, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user