/
product_cache_repository.go
90 lines (70 loc) · 2.36 KB
/
product_cache_repository.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package postgres
import (
"context"
"database/sql"
"fmt"
"github.com/jackc/pgconn"
"github.com/jackc/pgerrcode"
"github.com/stackus/errors"
"github.com/LordMoMA/Intelli-Mall/internal/postgres"
"github.com/LordMoMA/Intelli-Mall/search/internal/application"
"github.com/LordMoMA/Intelli-Mall/search/internal/models"
)
type ProductCacheRepository struct {
tableName string
db postgres.DB
fallback application.ProductRepository
}
var _ application.ProductCacheRepository = (*ProductCacheRepository)(nil)
func NewProductCacheRepository(tableName string, db postgres.DB, fallback application.ProductRepository) ProductCacheRepository {
return ProductCacheRepository{
tableName: tableName,
db: db,
fallback: fallback,
}
}
func (r ProductCacheRepository) Add(ctx context.Context, productID, storeID, name string) error {
const query = `INSERT INTO %s (id, store_id, NAME) VALUES ($1, $2, $3)`
_, err := r.db.ExecContext(ctx, r.table(query), productID, storeID, name)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == pgerrcode.UniqueViolation {
return nil
}
}
}
return err
}
func (r ProductCacheRepository) Rebrand(ctx context.Context, productID, name string) error {
const query = `UPDATE %s SET NAME = $2 WHERE id = $1`
_, err := r.db.ExecContext(ctx, r.table(query), productID, name)
return err
}
func (r ProductCacheRepository) Remove(ctx context.Context, productID string) error {
const query = `DELETE FROM %s WHERE id = $1`
_, err := r.db.ExecContext(ctx, r.table(query), productID)
return err
}
func (r ProductCacheRepository) Find(ctx context.Context, productID string) (*models.Product, error) {
const query = `SELECT store_id, name FROM %s WHERE id = $1 LIMIT 1`
product := &models.Product{
ID: productID,
}
err := r.db.QueryRowContext(ctx, r.table(query), productID).Scan(&product.StoreID, &product.Name)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return nil, errors.Wrap(err, "scanning product")
}
product, err = r.fallback.Find(ctx, productID)
if err != nil {
return nil, errors.Wrap(err, "product fallback failed")
}
// attempt to add it to the cache
return product, r.Add(ctx, product.ID, product.StoreID, product.Name)
}
return product, nil
}
func (r ProductCacheRepository) table(query string) string {
return fmt.Sprintf(query, r.tableName)
}