infra.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. id uint,
  34. ) (*models.Infra, error) {
  35. if !repo.canQuery {
  36. return nil, errors.New("Cannot read from database")
  37. }
  38. if int(id-1) >= len(repo.infras) || repo.infras[id-1] == nil {
  39. return nil, gorm.ErrRecordNotFound
  40. }
  41. index := int(id - 1)
  42. return repo.infras[index], nil
  43. }
  44. // ListInfrasByProjectID finds all aws infras
  45. // for a given project id
  46. func (repo *InfraRepository) ListInfrasByProjectID(
  47. projectID uint,
  48. ) ([]*models.Infra, error) {
  49. if !repo.canQuery {
  50. return nil, errors.New("Cannot read from database")
  51. }
  52. res := make([]*models.Infra, 0)
  53. for _, infra := range repo.infras {
  54. if infra != nil && infra.ProjectID == projectID {
  55. res = append(res, infra)
  56. }
  57. }
  58. return res, nil
  59. }
  60. // UpdateInfra modifies an existing Infra in the database
  61. func (repo *InfraRepository) UpdateInfra(
  62. ai *models.Infra,
  63. ) (*models.Infra, error) {
  64. if !repo.canQuery {
  65. return nil, errors.New("Cannot write database")
  66. }
  67. if int(ai.ID-1) >= len(repo.infras) || repo.infras[ai.ID-1] == nil {
  68. return nil, gorm.ErrRecordNotFound
  69. }
  70. index := int(ai.ID - 1)
  71. repo.infras[index] = ai
  72. return ai, nil
  73. }