92 lines
1.8 KiB
Go
92 lines
1.8 KiB
Go
package link
|
|
|
|
import (
|
|
apperrors "cgnolink/errors"
|
|
"github.com/patrickmn/go-cache"
|
|
"time"
|
|
)
|
|
|
|
type Service interface {
|
|
Create(link *Link) error
|
|
GetById(id string) (*Link, error)
|
|
GetAll(limit int, offset int) (Links, error)
|
|
Update(data *Link) error
|
|
DeleteById(id string) error
|
|
}
|
|
|
|
type PgService struct {
|
|
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 {
|
|
existingLink, err := s.rep.FindById(link.Id)
|
|
if err != nil {
|
|
return apperrors.UnknownError{Err: err}
|
|
}
|
|
|
|
if existingLink != nil {
|
|
return apperrors.AlreadyExistsError{Message: "Link with given ID already exists."}
|
|
}
|
|
|
|
if err = s.rep.Save(link); err != nil {
|
|
return apperrors.UnknownError{Err: err}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
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}
|
|
}
|
|
|
|
if link == nil {
|
|
return nil, apperrors.NotFoundError{Message: "Link with given ID was not found."}
|
|
}
|
|
|
|
s.cache.Set(id, link, 0)
|
|
|
|
return link, nil
|
|
}
|
|
|
|
func (s *PgService) GetAll(limit int, offset int) (Links, error) {
|
|
links, err := s.rep.FindAll(limit, offset)
|
|
if err != nil {
|
|
return nil, apperrors.UnknownError{Err: err}
|
|
}
|
|
|
|
return links, nil
|
|
}
|
|
|
|
func (s *PgService) Update(data *Link) error {
|
|
if err := s.rep.Update(data); err != nil {
|
|
return apperrors.UnknownError{Err: err}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *PgService) DeleteById(id string) error {
|
|
s.cache.Delete(id)
|
|
|
|
if err := s.rep.DeleteById(id); err != nil {
|
|
return apperrors.UnknownError{Err: err}
|
|
}
|
|
|
|
return nil
|
|
}
|