session.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // SessionRepository uses gorm.DB for querying the database
  9. type SessionRepository struct {
  10. canQuery bool
  11. sessions []*models.Session
  12. }
  13. // NewSessionRepository returns pointer to repo along with the db
  14. func NewSessionRepository(canQuery bool) repository.SessionRepository {
  15. return &SessionRepository{canQuery, []*models.Session{}}
  16. }
  17. // CreateSession must take in Key, Data, and ExpiresAt as arguments.
  18. func (repo *SessionRepository) CreateSession(session *models.Session) (*models.Session, error) {
  19. if !repo.canQuery {
  20. return nil, errors.New("Cannot write database")
  21. }
  22. // make sure key doesn't exist
  23. for _, s := range repo.sessions {
  24. if s.Key == session.Key {
  25. return nil, errors.New("Cannot write database")
  26. }
  27. }
  28. sessions := repo.sessions
  29. sessions = append(sessions, session)
  30. repo.sessions = sessions
  31. session.ID = uint(len(repo.sessions))
  32. return session, nil
  33. }
  34. // UpdateSession updates only the Data field using Key as selector.
  35. func (repo *SessionRepository) UpdateSession(session *models.Session) (*models.Session, error) {
  36. if !repo.canQuery {
  37. return nil, errors.New("Cannot write database")
  38. }
  39. var oldSession *models.Session
  40. for _, s := range repo.sessions {
  41. if s.Key == session.Key {
  42. oldSession = s
  43. }
  44. }
  45. if oldSession != nil {
  46. oldSession.Data = session.Data
  47. return oldSession, nil
  48. }
  49. return nil, gorm.ErrRecordNotFound
  50. }
  51. // DeleteSession deletes a session by Key
  52. func (repo *SessionRepository) DeleteSession(session *models.Session) (*models.Session, error) {
  53. if !repo.canQuery {
  54. return nil, errors.New("Cannot write database")
  55. }
  56. if int(session.ID-1) >= len(repo.sessions) || repo.sessions[session.ID-1] == nil {
  57. return nil, gorm.ErrRecordNotFound
  58. }
  59. index := int(session.ID - 1)
  60. repo.sessions[index] = nil
  61. return session, nil
  62. }
  63. // SelectSession returns a session with matching key
  64. func (repo *SessionRepository) SelectSession(session *models.Session) (*models.Session, error) {
  65. if !repo.canQuery {
  66. return nil, errors.New("Cannot write database")
  67. }
  68. for _, s := range repo.sessions {
  69. if s.Key == session.Key {
  70. return s, nil
  71. }
  72. }
  73. return nil, gorm.ErrRecordNotFound
  74. }