memory.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package infrastructure
  2. import (
  3. "code.osinet.fr/fgm/kurz/domain"
  4. "github.com/nicksnyder/go-i18n/v2/i18n"
  5. )
  6. type urlmap map[domain.URL]domain.URL
  7. var shortRepo = MemoryShortURLRepository{make(urlmap)}
  8. var targetRepo = MemoryTargetURLRepository{make(urlmap)}
  9. type MemoryShortURLRepository struct {
  10. targets urlmap
  11. }
  12. type MemoryTargetURLRepository struct {
  13. shorts urlmap
  14. }
  15. func (sr MemoryShortURLRepository) GetTarget(su domain.ShortURL, localizer *i18n.Localizer) (domain.TargetURL, error) {
  16. var tu domain.TargetURL
  17. var err error
  18. if t, ok := sr.targets[su.URL]; ok {
  19. tu = domain.TargetURL{URL: t}
  20. } else {
  21. err = domain.MakeError(nil, domain.ShortNotFound.ID, "")
  22. }
  23. return tu, err
  24. }
  25. func (tr MemoryTargetURLRepository) GetShort(tu domain.TargetURL) (su domain.ShortURL, isNew bool, err error) {
  26. // If short exists, just return it.
  27. if s, ok := tr.shorts[tu.URL]; ok {
  28. su = domain.ShortURL{URL: s}
  29. return su, false, err
  30. }
  31. // If it doesn't exist, attempt to create it.
  32. su, err = domain.NewUnspecifiedShortURL(tu)
  33. if err != nil {
  34. // Creation failed.
  35. return su, false, err
  36. }
  37. tr.shorts[tu.URL] = su.URL
  38. shortRepo.targets[su.URL] = tu.URL
  39. return su, true, err
  40. }