/
counter.go
51 lines (44 loc) · 1.26 KB
/
counter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Package counter handles the logic of a counter.
package counter
import (
"context"
"database/sql"
"errors"
"github.com/Darkness4/auth-htmx/database"
)
// Repository defines the counter methods.
type Repository interface {
Inc(ctx context.Context, userID string) (new int64, err error)
Get(ctx context.Context, userID string) (int64, error)
}
// NewRepository wraps around a SQL database to execute the counter methods.
func NewRepository(db *sql.DB) Repository {
return &repository{
Queries: database.New(db),
}
}
type repository struct {
*database.Queries
}
// Inc increments the counter of a user in the database by one.
func (r *repository) Inc(ctx context.Context, userID string) (newValue int64, err error) {
newValue, err = r.Queries.IncrementCounter(ctx, userID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return newValue, err
}
if errors.Is(err, sql.ErrNoRows) {
return 1, r.Queries.CreateCounter(ctx, userID)
}
return newValue, err
}
// Get the value of the counter of a user from the database.
func (r *repository) Get(ctx context.Context, userID string) (int64, error) {
counter, err := r.Queries.GetCounter(ctx, userID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, nil
}
return 0, err
}
return counter.Count, nil
}