Интернет-магазин: Go, PostgreSQL 17 SSL, Caddy, Docker Compose
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"shop/internal/models"
|
||||
)
|
||||
|
||||
type ProductRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewProductRepository(pool *pgxpool.Pool) *ProductRepository {
|
||||
return &ProductRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ProductRepository) Featured(ctx context.Context, limit int) ([]models.Product, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT id, name, description, price, image_url, category, featured
|
||||
FROM products
|
||||
WHERE featured = true
|
||||
ORDER BY id
|
||||
LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []models.Product
|
||||
for rows.Next() {
|
||||
var p models.Product
|
||||
if err := rows.Scan(&p.ID, &p.Name, &p.Description, &p.Price, &p.ImageURL, &p.Category, &p.Featured); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, p)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (r *ProductRepository) Categories(ctx context.Context) ([]string, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT DISTINCT category FROM products ORDER BY category`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var cats []string
|
||||
for rows.Next() {
|
||||
var c string
|
||||
if err := rows.Scan(&c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cats = append(cats, c)
|
||||
}
|
||||
return cats, rows.Err()
|
||||
}
|
||||
|
||||
func (r *ProductRepository) Count(ctx context.Context) (int, error) {
|
||||
var n int
|
||||
err := r.pool.QueryRow(ctx, `SELECT COUNT(*) FROM products`).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
Reference in New Issue
Block a user