sp.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package sp
  2. import (
  3. "github.com/dmitriygnatenko/internal/interfaces"
  4. "github.com/dmitriygnatenko/internal/repositories"
  5. cacheService "github.com/dmitriygnatenko/internal/services/cache"
  6. dbService "github.com/dmitriygnatenko/internal/services/db"
  7. envService "github.com/dmitriygnatenko/internal/services/env"
  8. mailService "github.com/dmitriygnatenko/internal/services/mailer"
  9. )
  10. type ServiceProvider struct {
  11. env interfaces.Env
  12. cache interfaces.Cache
  13. mailer interfaces.Mailer
  14. articleRepository interfaces.ArticleRepository
  15. tagRepository interfaces.TagRepository
  16. articleTagRepository interfaces.ArticleTagRepository
  17. }
  18. func Init() (interfaces.ServiceProvider, error) {
  19. sp := &ServiceProvider{}
  20. // Init services
  21. env, err := envService.Init()
  22. if err != nil {
  23. return nil, err
  24. }
  25. sp.env = env
  26. cache, err := cacheService.Init()
  27. if err != nil {
  28. return nil, err
  29. }
  30. sp.cache = cache
  31. mailer, err := mailService.Init(sp.env)
  32. if err != nil {
  33. return nil, err
  34. }
  35. sp.mailer = mailer
  36. db, err := dbService.Init(env)
  37. if err != nil {
  38. return nil, err
  39. }
  40. // Init repositories
  41. sp.articleRepository = repositories.InitArticleRepository(db)
  42. sp.tagRepository = repositories.InitTagRepository(db)
  43. sp.articleTagRepository = repositories.InitArticleTagRepository(db)
  44. return sp, nil
  45. }
  46. func (sp *ServiceProvider) GetEnvService() interfaces.Env {
  47. return sp.env
  48. }
  49. func (sp *ServiceProvider) GetCacheService() interfaces.Cache {
  50. return sp.cache
  51. }
  52. func (sp *ServiceProvider) GetMailerService() interfaces.Mailer {
  53. return sp.mailer
  54. }
  55. func (sp *ServiceProvider) GetArticleRepository() interfaces.ArticleRepository {
  56. return sp.articleRepository
  57. }
  58. func (sp *ServiceProvider) GetTagRepository() interfaces.TagRepository {
  59. return sp.tagRepository
  60. }
  61. func (sp *ServiceProvider) GetArticleTagRepository() interfaces.ArticleTagRepository {
  62. return sp.articleTagRepository
  63. }
  64. func InitMock(deps ...interface{}) interfaces.ServiceProvider {
  65. sp := ServiceProvider{}
  66. for _, d := range deps {
  67. switch s := d.(type) {
  68. case interfaces.Cache:
  69. sp.cache = s
  70. case interfaces.Env:
  71. sp.env = s
  72. case interfaces.Mailer:
  73. sp.mailer = s
  74. case interfaces.ArticleRepository:
  75. sp.articleRepository = s
  76. case interfaces.ArticleTagRepository:
  77. sp.articleTagRepository = s
  78. case interfaces.TagRepository:
  79. sp.tagRepository = s
  80. }
  81. }
  82. return &sp
  83. }