infra.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package test
  2. import (
  3. "errors"
  4. "github.com/porter-dev/porter/internal/models"
  5. "github.com/porter-dev/porter/internal/repository"
  6. "gorm.io/gorm"
  7. )
  8. // InfraRepository implements repository.InfraRepository
  9. type InfraRepository struct {
  10. canQuery bool
  11. infras []*models.Infra
  12. }
  13. // NewInfraRepository will return errors if canQuery is false
  14. func NewInfraRepository(canQuery bool) repository.InfraRepository {
  15. return &InfraRepository{
  16. canQuery,
  17. []*models.Infra{},
  18. }
  19. }
  20. // CreateInfra creates a new aws infra
  21. func (repo *InfraRepository) CreateInfra(
  22. infra *models.Infra,
  23. ) (*models.Infra, error) {
  24. if !repo.canQuery {
  25. return nil, errors.New("Cannot write database")
  26. }
  27. repo.infras = append(repo.infras, infra)
  28. infra.ID = uint(len(repo.infras))
  29. return infra, nil
  30. }
  31. // ReadInfra finds a aws infra by id
  32. func (repo *InfraRepository) ReadInfra(
  33. projectID,
  34. id uint,
  35. ) (*models.Infra, error) {
  36. if !repo.canQuery {
  37. return nil, errors.New("Cannot read from database")
  38. }
  39. if int(id-1) >= len(repo.infras) || repo.infras[id-1] == nil {
  40. return nil, gorm.ErrRecordNotFound
  41. }
  42. index := int(id - 1)
  43. return repo.infras[index], nil
  44. }
  45. // ListInfrasByProjectID finds all aws infras
  46. // for a given project id
  47. func (repo *InfraRepository) ListInfrasByProjectID(
  48. projectID uint,
  49. ) ([]*models.Infra, error) {
  50. if !repo.canQuery {
  51. return nil, errors.New("Cannot read from database")
  52. }
  53. res := make([]*models.Infra, 0)
  54. for _, infra := range repo.infras {
  55. if infra != nil && infra.ProjectID == projectID {
  56. res = append(res, infra)
  57. }
  58. }
  59. return res, nil
  60. }
  61. // UpdateInfra modifies an existing Infra in the database
  62. func (repo *InfraRepository) UpdateInfra(
  63. ai *models.Infra,
  64. ) (*models.Infra, error) {
  65. if !repo.canQuery {
  66. return nil, errors.New("Cannot write database")
  67. }
  68. if int(ai.ID-1) >= len(repo.infras) || repo.infras[ai.ID-1] == nil {
  69. return nil, gorm.ErrRecordNotFound
  70. }
  71. index := int(ai.ID - 1)
  72. repo.infras[index] = ai
  73. return ai, nil
  74. }