From 5741babc70feef1bc8a137a5ce0ef56fac727850 Mon Sep 17 00:00:00 2001 From: GalvinGao Date: Fri, 10 Feb 2023 15:23:18 -0500 Subject: [PATCH] refactor: use db selector --- internal/repo/activity.go | 23 ++++++++--------------- internal/repo/snapshot.go | 8 ++++---- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/internal/repo/activity.go b/internal/repo/activity.go index 9dfc6d29..37d256e2 100644 --- a/internal/repo/activity.go +++ b/internal/repo/activity.go @@ -2,32 +2,25 @@ package repo import ( "context" - "database/sql" - "github.com/pkg/errors" "github.com/uptrace/bun" "exusiai.dev/backend-next/internal/model" + "exusiai.dev/backend-next/internal/repo/selector" ) type Activity struct { - DB *bun.DB + db *bun.DB + + sel selector.S[model.Activity] } func NewActivity(db *bun.DB) *Activity { - return &Activity{DB: db} + return &Activity{db: db, sel: selector.New[model.Activity](db)} } func (c *Activity) GetActivities(ctx context.Context) ([]*model.Activity, error) { - var activities []*model.Activity - err := c.DB.NewSelect(). - Model(&activities). - Order("activity_id ASC"). - Scan(ctx) - - if err != nil && !errors.Is(err, sql.ErrNoRows) { - return nil, err - } - - return activities, nil + return c.sel.SelectMany(ctx, func(q *bun.SelectQuery) *bun.SelectQuery { + return q.Order("activity_id ASC") + }) } diff --git a/internal/repo/snapshot.go b/internal/repo/snapshot.go index bfda3554..dc426bad 100644 --- a/internal/repo/snapshot.go +++ b/internal/repo/snapshot.go @@ -10,14 +10,14 @@ import ( ) type Snapshot struct { - sel selector.S[model.Snapshot] + db *bun.DB - DB *bun.DB + sel selector.S[model.Snapshot] } func NewSnapshot(db *bun.DB) *Snapshot { return &Snapshot{ - DB: db, + db: db, sel: selector.New[model.Snapshot](db), } } @@ -47,7 +47,7 @@ func (s *Snapshot) GetSnapshotsByVersions(ctx context.Context, key string, versi } func (s *Snapshot) SaveSnapshot(ctx context.Context, snapshot *model.Snapshot) (*model.Snapshot, error) { - _, err := s.DB.NewInsert(). + _, err := s.db.NewInsert(). Model(snapshot). Exec(ctx) if err != nil {