stufflog graphql server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.3 KiB

  1. package mysqldriver
  2. import (
  3. "context"
  4. "database/sql"
  5. "git.aiterp.net/stufflog/server/internal/slerrors"
  6. "git.aiterp.net/stufflog/server/models"
  7. "github.com/jmoiron/sqlx"
  8. "time"
  9. )
  10. type sessionRepository struct {
  11. db *sqlx.DB
  12. }
  13. func (r *sessionRepository) Find(ctx context.Context, id string) (*models.Session, error) {
  14. session := models.Session{}
  15. err := r.db.GetContext(ctx, &session, "SELECT * FROM session WHERE session_id=?", id)
  16. if err != nil {
  17. if err == sql.ErrNoRows {
  18. return nil, slerrors.NotFound("Session")
  19. }
  20. return nil, err
  21. } else if time.Now().After(session.ExpiryTime) {
  22. return nil, slerrors.NotFound("Session")
  23. }
  24. return &session, nil
  25. }
  26. func (r *sessionRepository) Save(ctx context.Context, session models.Session) error {
  27. _, err := r.db.NamedExecContext(ctx, `
  28. REPLACE INTO session (session_id, user_id, expiry_time)
  29. VALUES (:session_id, :user_id, :expiry_time)
  30. `, session)
  31. return err
  32. }
  33. func (r *sessionRepository) Delete(ctx context.Context, session models.Session) error {
  34. _, err := r.db.ExecContext(ctx, "DELETE FROM session WHERE session_id=?", session.ID)
  35. return err
  36. }
  37. func (r *sessionRepository) DeleteExpired(ctx context.Context) error {
  38. _, err := r.db.ExecContext(ctx, "DELETE FROM session WHERE expiry_time<?", time.Now())
  39. return err
  40. }