Add caching
This commit is contained in:
parent
f166ffab3c
commit
fe9b4b5f5f
4 changed files with 36 additions and 21 deletions
|
|
@ -2,6 +2,8 @@ package link
|
|||
|
||||
import (
|
||||
apperrors "cgnolink/errors"
|
||||
"github.com/patrickmn/go-cache"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Service interface {
|
||||
|
|
@ -12,7 +14,15 @@ type Service interface {
|
|||
}
|
||||
|
||||
type PgService struct {
|
||||
rep PgRepository
|
||||
rep PgRepository
|
||||
cache *cache.Cache
|
||||
}
|
||||
|
||||
func NewPgService(rep PgRepository) PgService {
|
||||
return PgService{
|
||||
rep: rep,
|
||||
cache: cache.New(1*time.Hour, 90*time.Minute),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PgService) Create(link *Link) error {
|
||||
|
|
@ -33,6 +43,12 @@ func (s *PgService) Create(link *Link) error {
|
|||
}
|
||||
|
||||
func (s *PgService) GetById(id string) (*Link, error) {
|
||||
if v, found := s.cache.Get(id); found {
|
||||
if link, ok := v.(*Link); ok {
|
||||
return link, nil
|
||||
}
|
||||
}
|
||||
|
||||
link, err := s.rep.FindById(id)
|
||||
if err != nil {
|
||||
return nil, apperrors.UnknownError{Err: err}
|
||||
|
|
@ -42,6 +58,8 @@ func (s *PgService) GetById(id string) (*Link, error) {
|
|||
return nil, apperrors.NotFoundError{Message: "Link with given ID was not found."}
|
||||
}
|
||||
|
||||
s.cache.Set(id, link, 0)
|
||||
|
||||
return link, nil
|
||||
}
|
||||
|
||||
|
|
@ -55,6 +73,8 @@ func (s *PgService) GetAll(limit int, offset int) (Links, error) {
|
|||
}
|
||||
|
||||
func (s *PgService) DeleteById(id string) error {
|
||||
s.cache.Delete(id)
|
||||
|
||||
if err := s.rep.DeleteById(id); err != nil {
|
||||
return apperrors.UnknownError{Err: err}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue