repoclient.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. // RepoClientRepository implements repository.RepoClientRepository
  9. type RepoClientRepository struct {
  10. canQuery bool
  11. repoClients []*models.RepoClient
  12. }
  13. // NewRepoClientRepository will return errors if canQuery is false
  14. func NewRepoClientRepository(canQuery bool) repository.RepoClientRepository {
  15. return &RepoClientRepository{
  16. canQuery,
  17. []*models.RepoClient{},
  18. }
  19. }
  20. // CreateRepoClient creates a new repo client and appends it to the in-memory list
  21. func (repo *RepoClientRepository) CreateRepoClient(rc *models.RepoClient) (*models.RepoClient, error) {
  22. if !repo.canQuery {
  23. return nil, errors.New("Cannot write database")
  24. }
  25. repo.repoClients = append(repo.repoClients, rc)
  26. rc.ID = uint(len(repo.repoClients))
  27. return rc, nil
  28. }
  29. // ReadRepoClient returns a repo client by id
  30. func (repo *RepoClientRepository) ReadRepoClient(id uint) (*models.RepoClient, error) {
  31. if !repo.canQuery {
  32. return nil, errors.New("Cannot read from database")
  33. }
  34. if int(id-1) >= len(repo.repoClients) || repo.repoClients[id-1] == nil {
  35. return nil, gorm.ErrRecordNotFound
  36. }
  37. index := int(id - 1)
  38. return repo.repoClients[index], nil
  39. }
  40. // ListRepoClientsByProjectID returns a list of repo clients that match a project id
  41. func (repo *RepoClientRepository) ListRepoClientsByProjectID(projectID uint) ([]*models.RepoClient, error) {
  42. if !repo.canQuery {
  43. return nil, errors.New("Cannot read from database")
  44. }
  45. res := make([]*models.RepoClient, 0)
  46. for _, rc := range repo.repoClients {
  47. if rc.ProjectID == projectID {
  48. res = append(res, rc)
  49. }
  50. }
  51. return res, nil
  52. }