sp.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package service_provider
  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.IEnv
  12. cache interfaces.ICache
  13. mailer interfaces.IMailer
  14. articleRepository interfaces.IArticleRepository
  15. tagRepository interfaces.ITagRepository
  16. articleTagRepository interfaces.IArticleTagRepository
  17. }
  18. func Init() (interfaces.IServiceProvider, error) {
  19. sp := &ServiceProvider{}
  20. // Init env service
  21. env, err := envService.Init()
  22. if err != nil {
  23. return nil, err
  24. }
  25. sp.env = env
  26. db, err := dbService.Init(env)
  27. if err != nil {
  28. return nil, err
  29. }
  30. // Init repositories
  31. sp.articleRepository = repositories.InitArticleRepository(db)
  32. sp.tagRepository = repositories.InitTagRepository(db)
  33. sp.articleTagRepository = repositories.InitArticleTagRepository(db)
  34. // Init cache service
  35. sp.cache = cacheService.Init()
  36. // Init mailer
  37. sp.mailer = mailService.Init(sp.env)
  38. return sp, nil
  39. }
  40. func (sp *ServiceProvider) GetEnvService() interfaces.IEnv {
  41. return sp.env
  42. }
  43. func (sp *ServiceProvider) GetCacheService() interfaces.ICache {
  44. return sp.cache
  45. }
  46. func (sp *ServiceProvider) GetMailerService() interfaces.IMailer {
  47. return sp.mailer
  48. }
  49. func (sp *ServiceProvider) GetArticleRepository() interfaces.IArticleRepository {
  50. return sp.articleRepository
  51. }
  52. func (sp *ServiceProvider) GetTagRepository() interfaces.ITagRepository {
  53. return sp.tagRepository
  54. }
  55. func (sp *ServiceProvider) GetArticleTagRepository() interfaces.IArticleTagRepository {
  56. return sp.articleTagRepository
  57. }
  58. func InitMock(deps ...interface{}) interfaces.IServiceProvider {
  59. sp := ServiceProvider{}
  60. for _, d := range deps {
  61. switch s := d.(type) {
  62. case interfaces.ICache:
  63. sp.cache = s
  64. case interfaces.IEnv:
  65. sp.env = s
  66. case interfaces.IMailer:
  67. sp.mailer = s
  68. case interfaces.IArticleRepository:
  69. sp.articleRepository = s
  70. case interfaces.IArticleTagRepository:
  71. sp.articleTagRepository = s
  72. case interfaces.ITagRepository:
  73. sp.tagRepository = s
  74. }
  75. }
  76. return &sp
  77. }