github.com/gudimz/urlShortener@v0.0.0-20230129195305-c8ee33059a67/internal/shorten/service.go (about) 1 package shorten 2 3 import ( 4 "context" 5 "github.com/google/uuid" 6 "github.com/gudimz/urlShortener/internal/model" 7 "time" 8 ) 9 10 type Storage interface { 11 CreateShorten(ctx context.Context, ms model.Shorten) error 12 GetShorten(ctx context.Context, shortUrl string) (*model.Shorten, error) 13 DeleteShorten(ctx context.Context, shortUrl string) (int64, error) 14 UpdateShorten(ctx context.Context, shortUrl string) error 15 } 16 17 type Service struct { 18 storage Storage 19 } 20 21 func NewService(storage Storage) *Service { 22 return &Service{ 23 storage: storage, 24 } 25 } 26 27 func (s *Service) CreateShorten(ctx context.Context, input model.InputShorten) (*model.Shorten, error) { 28 var ( 29 id = uuid.New().ID() 30 shortUrl = input.ShortenUrl.OrElse(GenerateShortenUrl(id)) 31 ) 32 33 shorten := model.Shorten{ 34 ShortUrl: shortUrl, 35 OriginUrl: input.OriginUrl, 36 Visits: 0, 37 DateCreated: time.Now().UTC(), 38 DateUpdated: time.Now().UTC(), 39 } 40 41 err := s.storage.CreateShorten(ctx, shorten) 42 if err != nil { 43 return nil, err 44 } 45 46 return &shorten, nil 47 } 48 49 func (s *Service) GetShorten(ctx context.Context, shortUrl string) (*model.Shorten, error) { 50 shorten, err := s.storage.GetShorten(ctx, shortUrl) 51 if err != nil { 52 return nil, err 53 } 54 return shorten, nil 55 } 56 57 func (s *Service) Redirect(ctx context.Context, shortUrl string) (string, error) { 58 shorten, err := s.storage.GetShorten(ctx, shortUrl) 59 if err != nil { 60 return "", err 61 } 62 63 err = s.storage.UpdateShorten(ctx, shortUrl) 64 if err != nil { 65 return shorten.OriginUrl, err 66 } 67 68 return shorten.OriginUrl, nil 69 } 70 71 func (s *Service) DeleteShorten(ctx context.Context, shortUrl string) (int64, error) { 72 return s.storage.DeleteShorten(ctx, shortUrl) 73 }